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


当前回答

先取xml中的Button。

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

制作按钮的监听器。

 pre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });

其他回答

为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

虽然已经提供了正确的答案,但我在这里搜索语言Kotlin的答案。这个问题不是关于特定于语言的,所以我添加代码来完成这个任务在Kotlin语言。

下面是如何在Kotlin中为andorid做到这一点

testActivityBtn1.setOnClickListener{
      val intent = Intent(applicationContext,MainActivity::class.java)
      startActivity(intent)

 }

实现视图。OnClickListener接口,并重写onClick方法。

ImageView btnSearch;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search1);
        ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(this);
    }

@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSearch: {
                Intent intent = new Intent(Search.this,SearchFeedActivity.class);
                startActivity(intent);
                break;
            }

科特林

第一个活动

startActivity(Intent(this, SecondActivity::class.java)
  .putExtra("key", "value"))

第二个活动

val value = getIntent().getStringExtra("key")

建议

总是把钥匙放在固定的文件,以更有管理的方式。

companion object {
    val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
  .putExtra(PUT_EXTRA_USER, "value"))

一件容易的事。

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);

额外的内容可以通过以下方式从另一侧检索:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("key"); //if it's a string you stored.
}

不要忘记在AndroidManifest.xml中添加你的新活动:

<activity android:label="@string/app_name" android:name="NextActivity"/>