在Android应用程序中,当单击另一个活动中的按钮时,如何启动一个新活动(GUI),以及如何在这两个活动之间传递数据?
当前回答
虽然已经提供了正确的答案,但我在这里搜索语言Kotlin的答案。这个问题不是关于特定于语言的,所以我添加代码来完成这个任务在Kotlin语言。
下面是如何在Kotlin中为andorid做到这一点
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
其他回答
在发送活动中尝试以下代码
//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"
当用户点击按钮时,直接在XML中,就像这样:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextButton"
android:onClick="buttonClickFunction"/>
使用属性android:onClick我们声明方法名必须出现在父活动上。所以我必须在我们的活动中创建这个方法,像这样:
public void buttonClickFunction(View v)
{
Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
startActivity(intent);
}
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
你可以试试下面的代码:
Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
虽然已经提供了正确的答案,但我在这里搜索语言Kotlin的答案。这个问题不是关于特定于语言的,所以我添加代码来完成这个任务在Kotlin语言。
下面是如何在Kotlin中为andorid做到这一点
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。