在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
});
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。