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


当前回答

Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);

其他回答

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

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

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

 }
Button button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SplashActivity.this,HomeActivity.class);
            startActivity(intent);
        }
    });

像下面这样在xml中放置按钮小部件

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
/>

在此之后,初始化和处理点击监听器在活动如下..

在Activity On Create方法中:

Button button =(Button) findViewById(R.id.button); 
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       Intent intent = new 
            Intent(CurrentActivity.this,DesiredActivity.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
 imageView.setOnClickListener(v -> {
// your code here
        });