How to start new activity on button click

2018-12-31 01:08发布

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

21条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 01:45

The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.

查看更多
临风纵饮
3楼-- · 2018-12-31 01:45

Take Button in xml first.

  <Button
        android:id="@+id/pre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher"
        android:text="Your Text"
        />

Make listner of button.

 pre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 01:48

You can try this code:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
查看更多
美炸的是我
5楼-- · 2018-12-31 01:49

Try this simple method.

startActivity(new Intent(MainActivity.this, SecondActivity.class));
查看更多
临风纵饮
6楼-- · 2018-12-31 01:49

When button is clicked:

loginBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent= new Intent(getApplicationContext(), NextActivity.class);
        intent.putExtra("data", value); //pass data
        startActivity(intent);
    }
});

To received the extra data from NextActivity.class :

Bundle extra = getIntent().getExtras();
if (extra != null){
    String str = (String) extra.get("data"); // get a object
}
查看更多
低头抚发
7楼-- · 2018-12-31 01:51

Emmanuel,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);
查看更多
登录 后发表回答