如何在按钮单击时启动新活动

Adh*_*ham 596 android android-intent android-lifecycle android-button android-activity

在Android应用程序中,如何在单击其他活动中的按钮时启动新活动(GUI),以及如何在这两个活动之间传递数据?

Emm*_*uel 1062

简单.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Run Code Online (Sandbox Code Playgroud)

通过以下方式检索额外内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Run Code Online (Sandbox Code Playgroud)

不要忘记在AndroidManifest.xml中添加新活动:

<activity android:label="@string/app_name" android:name="NextActivity"/>
Run Code Online (Sandbox Code Playgroud)

  • 液体,你想让他把它打包成一个apk吗?;) (99认同)
  • 按钮单击部分在哪里?(按钮单击→转换到下一个活动) (17认同)
  • `CurrentActivity.this.startActivity(myIntent)`和`startActivity(myIntent)`之间有什么区别吗? (6认同)
  • @Jonny:这是按钮点击的一个例子.http://stackoverflow.com/a/7722428/442512 (4认同)
  • 是的,很容易哈哈.代码丢失比实际输入的代码多.所有xml接口和.java代码都丢失在哪里?Downvote (4认同)
  • 值得一提的是,您还可以使用 CurrentActivity.this.finish(); 在最后。有时,当您重定向用户并且他按下后退按钮时,您不希望用户最终陷入某些与错误相关的活动。Finish() 方法的作用是销毁当前活动。 (3认同)

Bry*_*nny 57

创建ViewPerson活动的intent并传递PersonID(例如,用于数据库查找).

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

然后在ViewPerson Activity中,您可以获取额外数据包,确保它不为空(如果您有时不传递数据),然后获取数据.

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您需要在两个活动之间共享数据,您还可以拥有一个Global Singleton.

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}
Run Code Online (Sandbox Code Playgroud)

然后在以下任何活动中调用它:

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
Run Code Online (Sandbox Code Playgroud)


Mar*_*ing 54

目前的反应很好,但初学者需要更全面的答案.在Android中有三种不同的方式来启动新活动,它们都使用Intent该类; 意图| Android开发者.

  1. 使用onClickButton 的属性.(初学者)
  2. OnClickListener()通过匿名类分配.(中间)
  3. 使用switch语句的活动宽接口方法.(专业版)

如果您想跟随我的示例链接:https://github.com/martinsing/ToNewActivityButtons

1.使用onClickButton 的属性.(初学者)

按钮具有onClick在.xml文件中找到的属性:

<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" />
Run Code Online (Sandbox Code Playgroud)

在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);
}
Run Code Online (Sandbox Code Playgroud)

优点:易于即时制作,模块化,并且可以轻松地将多个onClicks设置为相同的意图.

缺点:审查时难以阅读.

2. OnClickListener()通过匿名类分配.(中间)

这是当你setOnClickListener()为每个设置一个单独的,buttononClick()用自己的意图覆盖每个.

在Java类中:

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        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);}
            });

        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);}
            });
Run Code Online (Sandbox Code Playgroud)

优点:易于制作.

缺点:会有很多匿名类在审阅时会使可读性变得困难.

3.使用switch语句的活动宽接口方法.(专业版)

这是当您switchonClick()方法中使用按钮语句来管理所有Activity的按钮时.

在Java类中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    button1 = (Button) findViewById(R.id.button1);
    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;
    }
Run Code Online (Sandbox Code Playgroud)

优点:简单的按钮管理,因为所有按钮意图都在一个onClick()方法中注册


对于问题的第二部分,传递数据,请参阅如何在Android应用程序中的活动之间传递数据?

  • #3不是“亲”。这是可读性和可维护性最差的选项,第一个看到它的经验丰富的开发人员会将其重构为#1或#2。(否则,他们将使用Butterknife,这是类固醇的选择#1。) (3认同)
  • 3绝对不是“专业” (2认同)

Int*_*iya 36

当用户点击按钮时,直接在XML内部:

<Button
         android:id="@+id/button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="TextButton"
         android:onClick="buttonClickFunction"/>
Run Code Online (Sandbox Code Playgroud)

使用该属性,android:onClick我们声明必须存在于父活动上的方法名称.所以我必须在我们的活动中创建这样的方法:

public void buttonClickFunction(View v)
{
            Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
            startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)


小智 19

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);
Run Code Online (Sandbox Code Playgroud)

  • 这只是部分答案.而且它还不够,即如果没有项目中的额外修改,它将无法工作. (2认同)

use*_*551 10

    Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);    
    startActivity(in);

    This is an explicit intent to start secondscreen activity.
Run Code Online (Sandbox Code Playgroud)


小智 8

灵光,

我认为应该在开始活动之前放置额外的信息,否则如果您在NextActivity的onCreate方法中访问它,则数据将不可用.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);
Run Code Online (Sandbox Code Playgroud)


Ale*_*bor 7

从发送活动尝试以下代码

   //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);

            }
Run Code Online (Sandbox Code Playgroud)

从接收活动中尝试以下代码:

   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);
Run Code Online (Sandbox Code Playgroud)

然后只需将以下代码添加到AndroidManifest.xml文件中

  android:name="packagename.NameOfTheReceivingActivity"
  android:label="Title of the Activity"
  android:parentActivityName="packagename.NameOfSendingActivity"
Run Code Online (Sandbox Code Playgroud)


Mah*_*tab 7

Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)


Roh*_*ngh 6

从另一个 Activity 启动一个 Activity 在 Android 应用程序中是很常见的情况。
要启动一个活动,您需要一个Intent对象。

如何创建Intent对象?

意图对象在其构造函数中采用两个参数

  1. 语境
  2. 要启动的活动的名称。(或完整的包名称)

例子:

在此输入图像描述

例如,如果您有两个活动,例如HomeActivity和您想从(HomeActivity-->DetailActivity)DetailActivity开始。DetailActivityHomeActivity

这是显示如何启动 DetailActivity 的代码片段

家庭活动。

Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

你就完成了。

回到按钮点击部分。

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);  
      }

});
Run Code Online (Sandbox Code Playgroud)


Bri*_*oll 5

启动新活动的方法是广播意图,并且可以使用一种特定类型的意图将数据从一个活动传递到另一个活动。我的建议是您查看与意图相关的 Android 开发人员文档;它提供了有关该主题的大量信息,并且还有示例。


小智 5

您可以尝试以下代码:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);
Run Code Online (Sandbox Code Playgroud)


小智 5

试试这个简单的方法。

startActivity(new Intent(MainActivity.this, SecondActivity.class));
Run Code Online (Sandbox Code Playgroud)


Khe*_*raj 5

科特林

第一次活动

startActivity(Intent(this, SecondActivity::class.java)
  .putExtra("key", "value"))
Run Code Online (Sandbox Code Playgroud)

第二个活动

val value = getIntent().getStringExtra("key")
Run Code Online (Sandbox Code Playgroud)

建议

始终将密钥放在常量文件中以获得更多管理方式。

companion object {
    val PUT_EXTRA_USER = "user"
}
startActivity(Intent(this, SecondActivity::class.java)
  .putExtra(PUT_EXTRA_USER, "value"))
Run Code Online (Sandbox Code Playgroud)