在Android应用程序中,当单击另一个活动中的按钮时,如何启动一个新活动(GUI),以及如何在这两个活动之间传递数据?


当前回答

为ViewPerson活动创建一个意图并传递PersonID(例如,用于数据库查找)。

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);

然后在ViewPerson Activity中,你可以获得额外的数据包,确保它不为空(以防你有时不传递数据),然后获取数据。

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

现在如果你需要在两个activity之间共享数据,你也可以有一个全局单例。

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

然后在任何活动中调用它:

YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic

其他回答

点击按钮时:

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);
    }
});

从nex战术vity.class接收额外的数据:

Bundle extra = getIntent().getExtras();
if (extra != null){
    String str = (String) extra.get("data"); // get a object
}
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
    Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);    
    startActivity(in);

    This is an explicit intent to start secondscreen activity.

在第一个活动中编写代码。

button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
                       //You can use String ,arraylist ,integer ,float and all data type.
                       intent.putExtra("Key","value");
                       startActivity(intent);
                        finish();
            }
         });

在secondActivity.class

String name = getIntent().getStringExtra("Key");
Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);