[英]How to start new activity on button click
在 Android 应用程序中,如何在单击另一个活动中的按钮时启动新活动(GUI),以及如何在这两个活动之间传递数据?
简单。
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
通过以下方式在另一侧检索额外内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
不要忘记在 AndroidManifest.xml 中添加您的新活动:
<activity android:label="@string/app_name" android:name="NextActivity"/>
目前的反应很好,但初学者需要更全面的答案。 在 Android 中有 3 种不同的方式来启动一个新的 Activity,它们都使用Intent
类; 意图 | 安卓开发者。
onClick
属性。 (初学者)OnClickListener()
。 (中间的)switch
语句的活动范围接口方法。 (不是-“专业”)如果您想跟随,这是我的示例的链接:
onClick
属性。 (初学者) 按钮具有在 .xml 文件中找到的onClick
属性:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnActivity"
android:text="to an activity" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="goToAnotherActivity"
android:text="to another activity" />
在 Java 类中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void goToAnActivity(View view) {
Intent intent = new Intent(this, AnActivity.class);
startActivity(intent);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, AnotherActivity.class);
startActivity(intent);
}
优点:易于即时制作,模块化,并且可以轻松地将多个onClick
设置为相同的意图。
缺点:复习时可读性差。
OnClickListener()
。 (中间的) 这是当您为每个button
设置单独的setOnClickListener()
并以其自己的意图覆盖每个onClick()
时。
在 Java 类中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnActivity.class);
view.getContext().startActivity(intent);}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
view.getContext().startActivity(intent);}
});
优点:易于即时制作。
缺点:会有很多匿名类,在复习时会增加可读性。
switch
语句的活动范围接口方法。 (不是-“专业”) 这是当您在onClick()
方法中为您的按钮使用switch
语句来管理所有活动的按钮时。
在 Java 类中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent1 = new Intent(this, AnActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(this, AnotherActivity.class);
startActivity(intent2);
break;
default:
break;
}
优点:易于按钮管理,因为所有按钮意图都在单个onClick()
方法中注册
对于问题的第二部分,传递数据,请参阅如何在 Android 应用程序中的活动之间传递数据?
编辑:不是-“专业”
创建一个 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");
}
现在,如果您需要在两个活动之间共享数据,您还可以拥有一个全局单例。
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
当用户单击按钮时,直接在 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 iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
伊曼纽尔,
我认为应该在开始活动之前放置额外的信息,否则如果您在 NextActivity 的 onCreate 方法中访问数据,则数据将不可用。
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
从发送活动尝试以下代码
//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);
}
从接收 Activity 尝试以下代码:
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"
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
试试这个简单的方法。
startActivity(new Intent(MainActivity.this, SecondActivity.class));
你可以试试这个代码:
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"))
启动新活动的方法是广播一个意图,您可以使用一种特定类型的意图将数据从一个活动传递到另一个活动。 我的建议是您查看与意图相关的 Android 开发人员文档; 这是关于这个主题的大量信息,也有例子。
从另一个 Activity 启动一个 Activity 是 Android 应用程序中非常常见的场景。
要开始一项活动,您需要一个Intent对象。
意图对象在其构造函数中接受两个参数
例子:
例如,如果您有两个活动,比如说HomeActivity
和DetailActivity
并且您想从HomeActivity
(HomeActivity-->DetailActivity)启动DetailActivity
。
这是显示如何从 DetailActivity 启动的代码片段
家庭活动。
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
你已经完成了。
回到按钮点击部分。
Button button = (Button) findViewById(R.id.someid);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
}
});
从此活动开始另一个活动,您也可以通过捆绑对象传递参数。
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
在另一个活动 (YourActivity) 中检索数据
String s = getIntent().getStringExtra("USER_NAME");
// 在Kotlin 中,您可以这样做 /* 在第一个活动中,让活动布局中有一个 id 为按钮的按钮。 假设我必须将数据作为字符串类型从一个活动传递到另一个活动 */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// 在第二个活动中,您可以从另一个活动中获取数据作为
val name = intent.getStringExtra("KEY")
/* 假设你必须传递一个自定义对象,那么它应该是 Parcelable。 让我必须从一个活动传递到另一个活动的类拼贴类型 */
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
class Collage(val name: String, val mobile: String, val email: String) : Parcelable
/* Activity First,让这里的数据是拼贴类型。 我必须将其传递给另一个活动。 */
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val intent = Intent(baseContext, SecondActivity::class.java).apply {
putExtra("KEY", data)
}
startActivity(intent)
}
// 然后从第二个活动我们将得到
val item = intent.extras?.getParcelable<Collage>("KEY")
实现 View.OnClickListener 接口并覆盖 onClick 方法。
ImageView btnSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search1);
ImageView btnSearch = (ImageView) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSearch: {
Intent intent = new Intent(Search.this,SearchFeedActivity.class);
startActivity(intent);
break;
}
虽然已经提供了正确的答案,但我在这里搜索 Kotlin 语言的答案。 此问题与特定语言无关,因此我添加了代码以使用 Kotlin 语言完成此任务。
以下是在 Kotlin for andorid 中执行此操作的方法
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
单击按钮时打开活动的最简单方法是:
onclick
函数命名。主活动.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void goToAnotherActivity(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
第二个Activity.java
package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
}
}
AndroidManifest.xml(只需将此代码块添加到现有中)
</activity>
<activity android:name=".SecondActivity">
</activity>
首先在 xml 中获取 Button。
<Button
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
android:text="Your Text"
/>
制作按钮的监听器。
pre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.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);
}
});
从NextActivity.class
接收额外数据:
Bundle extra = getIntent().getExtras();
if (extra != null){
String str = (String) extra.get("data"); // get a object
}
在您的第一个活动中编写代码。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondAcitvity.class);
//You can use String ,arraylist ,integer ,float and all data type.
intent.putExtra("Key","value");
startActivity(intent);
finish();
}
});
在第二个Activity.class
String name = getIntent().getStringExtra("Key");
将按钮小部件放在 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);
}
});
一个老问题,但如果目标是切换显示的页面,我只有一个活动并在我想切换页面时调用 setContentView()(通常是为了响应用户单击按钮)。 这使我可以简单地从一个页面的内容调用到另一个。 没有意图的额外包裹捆绑和任何试图来回传递数据的精神错乱。
我像往常一样在 res/layout 中制作了一堆页面,但没有为每个页面制作活动。 只需使用 setContentView() 根据需要切换它们。
所以我唯一的 onCreate() 有:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater layoutInflater = getLayoutInflater();
final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
setContentView (mainPage);
Button openMenuButton = findViewById(R.id.openMenuButton);
final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
openMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(menuPage);
}
});
someMenuButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
do-something-interesting;
setContentView(mainPage);
}
}
}
如果您希望 Back 按钮在退出应用程序之前返回内部页面,只需将 setContentView() 包装起来以将页面保存在一小堆页面中,然后在 onBackPressed() 处理程序中弹出这些页面。
你的按钮xml:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="jump to activity b"
/>
主要活动.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);
}
});
imageView.setOnClickListener(v -> {
// your code here
});
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);
}
});
最简单的方法:
val a = Intent(this.context, BarcodeActivity::class.java)
a.putExtra("barcode", barcode)
startActivity(a)
在另一边(在我的例子中是 BarcodeActivity):
val intent: Intent = intent
var data = intent.getStringExtra("barcode")
在这里阅读更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.