在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
其他回答
启动新活动的方法是广播一个意图,您可以使用特定类型的意图将数据从一个活动传递到另一个活动。我的建议是你去看看Android开发者文档中与intent相关的内容;这是一个丰富的信息的主题,并有例子。
你可以试试下面的代码:
Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
科特林
第一个活动
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 iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
为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
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件