在Android应用程序中,当单击另一个活动中的按钮时,如何启动一个新活动(GUI),以及如何在这两个活动之间传递数据?
当前回答
Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
其他回答
imageView.setOnClickListener(v -> {
// your code here
});
在发送活动中尝试以下代码
//EXTRA_MESSAGE is our key and it's value is 'packagename.MESSAGE'
public static final String EXTRA_MESSAGE = "packageName.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
....
//Here we declare our send button
Button sendButton = (Button) findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//declare our intent object which takes two parameters, the context and the new activity name
// the name of the receiving activity is declared in the Intent Constructor
Intent intent = new Intent(getApplicationContext(), NameOfReceivingActivity.class);
String sendMessage = "hello world"
//put the text inside the intent and send it to another Activity
intent.putExtra(EXTRA_MESSAGE, sendMessage);
//start the activity
startActivity(intent);
}
从接收活动尝试以下代码:
protected void onCreate(Bundle savedInstanceState) {
//use the getIntent()method to receive the data from another activity
Intent intent = getIntent();
//extract the string, with the getStringExtra method
String message = intent.getStringExtra(NewActivityName.EXTRA_MESSAGE);
然后将以下代码添加到AndroidManifest.xml文件中
android:name="packagename.NameOfTheReceivingActivity"
android:label="Title of the Activity"
android:parentActivityName="packagename.NameOfSendingActivity"
启动新活动的方法是广播一个意图,您可以使用特定类型的意图将数据从一个活动传递到另一个活动。我的建议是你去看看Android开发者文档中与intent相关的内容;这是一个丰富的信息的主题,并有例子。
你的按钮xml:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump to activity b"
/>
Mainactivity.java:
Button btn=findViewVyId(R.id.btn);
btn.setOnClickListener(btnclick);
btnclick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(Mainactivity.this,b.class);
startActivity(intent);
}
});
点击按钮时:
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
}
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。