如何在按钮点击上启动新的活动?

时间:2021-05-24 20:43:03

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

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

17 个解决方案

#1


871  

Easy.

一件容易的事。

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

Extras are retrieved on the other side via:

临时演员通过以下方式获得:

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

Don't forget to add your new activity in the AndroidManifest.xml:

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

<activity android:label="@string/app_name" android:name="NextActivity"/>

#2


44  

Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).

创建一个ViewPerson活动的意图并传递PersonID(例如,用于数据库查找)。

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);

Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.

然后在ViewPerson活动中,您可以获得额外数据的包,确保它不是null(以防有时您不传递数据),然后获取数据。

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

Now if you need to share data between two Activities, you can also have a Global Singleton.

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

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

Then call it in any activity by:

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

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

#3


31  

Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.

现在的回答很好,但是对于初学者来说需要一个更全面的答案。在Android中有3种不同的启动新活动的方法,它们都使用Intent类;意图|安卓开发者。

  1. Using the onClick attribute of the Button. (Beginner)
  2. 使用按钮的onClick属性。(初学者)
  3. Assigning an OnClickListener() via an anonymous class. (Intermediate)
  4. 通过匿名类分配OnClickListener()。(中间)
  5. Activity wide interface method using the switch statement. (Pro)
  6. 使用switch语句的Activity wide接口方法。(职业)

Here's the link to my example if you want to follow along: https://github.com/martinsing/ToNewActivityButtons

下面是我的示例的链接,如果您想要遵循的话:https://github.com/martinsing/ToNewActivityButtons。

1. Using the onClick attribute of the Button. (Beginner)

Buttons have an onClick attribute that is found within the .xml file:

按钮的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" />

In Java class:

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

Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent easily.

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

Disadvantage: Difficult readability when reviewing.

缺点:复习时易读。

2. Assigning an OnClickListener() via an anonymous class. (Intermediate)

This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.

这是当您为每个按钮设置一个单独的setOnClickListener()时,并通过它自己的意图覆盖每个onClick()。

In Java class:

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

Advantage: Easy to make on the fly.

优点:容易做苍蝇。

Disadvantage: there will be a lot of anonymous classes which will make readability difficult when reviewing.

缺点:会有很多匿名类,在复习的时候会让可读性变得很困难。

3. Activity wide interface method using the switch statement. (Pro)

This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.

这是当您在onClick()方法中使用开关语句来管理所有活动的按钮时。

In Java class:

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

Advantage: Easy button management because all button intents are registered in a single onClick() method

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


For the second part of the question, passing data, please see How do I pass data between Activities in Android application?

对于问题的第二部分,传递数据,请查看我如何在Android应用程序之间传递数据。

#4


31  

When user clicks on the button, directly inside the XML like that:

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

<Button
         android:id="@+id/button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="TextButton"
         android:onClick="buttonClickFunction"/>

Using the attribute android:onClick we declare the method name that has to be present on the parent activity. So I have to create this method inside our activity like that:

使用属性android:onClick我们声明必须出现在父活动上的方法名。所以我必须在我们的活动中创建这个方法:

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

#5


15  

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

#6


8  

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

    This is an explicit intent to start secondscreen activity.

#7


7  

Emmanuel,

以马内利,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

我认为应该在开始活动之前添加额外的信息,否则数据将无法使用,如果您正在使用NextActivity的onCreate方法访问它。

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

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

#8


6  

From the sending Activity try the following code

从发送活动中尝试以下代码。

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

            }

From the receiving Activity try the following code:

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

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

Then just add the following code to the AndroidManifest.xml file

然后将以下代码添加到AndroidManifest。xml文件

  android:name="packagename.NameOfTheReceivingActivity"
  android:label="Title of the Activity"
  android:parentActivityName="packagename.NameOfSendingActivity"

#9


5  

Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);

#10


3  

The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.

启动新活动的方式是传播意图,并且有一种特定的意图,可以用来将数据从一个活动传递到另一个活动。我的建议是,您可以查看与意图相关的Android开发人员文档;这是一个关于这个主题的丰富的信息,也有一些例子。

#11


3  

You can try this code:

您可以试试下面的代码:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);

#12


3  

Try this simple method.

试试这个简单的方法。

startActivity(new Intent(MainActivity.this, SecondActivity.class));

#13


2  

Start another activity from this activity and u can pass parameters via Bundle Object also.

从这个活动开始另一个活动,u也可以通过Bundle对象传递参数。

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);

Retrive data in another activity (YourActivity)

在另一个活动(YourActivity)中检索数据

String s = getIntent().getStringExtra("USER_NAME");

#14


2  

Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an[Intent][1]object.

从另一个活动开始活动是android应用程序中非常常见的场景。要启动一个活动,需要一个[意图][1]对象。

How to create Intent Objects?

An intent object takes two parameter in its constructor

intent对象在其构造函数中接受两个参数。

  1. Context
  2. 上下文
  3. Name of the activity to be started.
  4. 要启动的活动的名称。

Example:

So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).

例如,如果你有两个活动,比如HomeActivity和DetailActivity,你想从HomeActivity (HomeActivity——>DetailActivity)中启动DetailActivity。

Here is the code snippet which shows how to start DetailActivity from

下面是代码片段,它展示了如何开始进行DetailActivity。

HomeActivity.

HomeActivity。

Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);

And you are done.

和你做。

Coming back to button click part.

回到按钮点击部分。

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

});

#15


1  

Implement the View.OnClickListener interface and override the onClick method.

实现视图。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;
            }

#16


1  

Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.

虽然已经提供了适当的答案,但我在这里是为了在Kotlin语言中寻找答案。这个问题不是关于语言的,所以我添加了代码来完成Kotlin语言的这个任务。

Here is how you do this in Kotlin for andorid

这是你在Kotlin为andorid做这个的方法。

testActivityBtn1.setOnClickListener{
      val intent = Intent(applicationContext,MainActivity::class.java)
      startActivity(intent)

 }

#17


0  

Take Button in xml first.

首先在xml中获取按钮。

  <Button
        android:id="@+id/pre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher"
        android:text="Your Text"
        />

Make listner of button.

使listner按钮。

 pre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });

#1


871  

Easy.

一件容易的事。

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

Extras are retrieved on the other side via:

临时演员通过以下方式获得:

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

Don't forget to add your new activity in the AndroidManifest.xml:

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

<activity android:label="@string/app_name" android:name="NextActivity"/>

#2


44  

Create an intent to a ViewPerson activity and pass the PersonID (for a database lookup, for example).

创建一个ViewPerson活动的意图并传递PersonID(例如,用于数据库查找)。

Intent i = new Intent(getBaseContext(), ViewPerson.class);                      
i.putExtra("PersonID", personID);
startActivity(i);

Then in ViewPerson Activity, you can get the bundle of extra data, make sure it isn't null (in case if you sometimes don't pass data), then get the data.

然后在ViewPerson活动中,您可以获得额外数据的包,确保它不是null(以防有时您不传递数据),然后获取数据。

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

Now if you need to share data between two Activities, you can also have a Global Singleton.

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

public class YourApplication extends Application 
{     
     public SomeDataClass data = new SomeDataClass();
}

Then call it in any activity by:

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

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

#3


31  

Current responses are great but a more comprehensive answer is needed for beginners. There are 3 different ways to start a new activity in Android, and they all use the Intent class; Intent | Android Developers.

现在的回答很好,但是对于初学者来说需要一个更全面的答案。在Android中有3种不同的启动新活动的方法,它们都使用Intent类;意图|安卓开发者。

  1. Using the onClick attribute of the Button. (Beginner)
  2. 使用按钮的onClick属性。(初学者)
  3. Assigning an OnClickListener() via an anonymous class. (Intermediate)
  4. 通过匿名类分配OnClickListener()。(中间)
  5. Activity wide interface method using the switch statement. (Pro)
  6. 使用switch语句的Activity wide接口方法。(职业)

Here's the link to my example if you want to follow along: https://github.com/martinsing/ToNewActivityButtons

下面是我的示例的链接,如果您想要遵循的话:https://github.com/martinsing/ToNewActivityButtons。

1. Using the onClick attribute of the Button. (Beginner)

Buttons have an onClick attribute that is found within the .xml file:

按钮的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" />

In Java class:

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

Advantage: Easy to make on the fly, modular, and can easily set multiple onClicks to the same intent easily.

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

Disadvantage: Difficult readability when reviewing.

缺点:复习时易读。

2. Assigning an OnClickListener() via an anonymous class. (Intermediate)

This is when you set a separate setOnClickListener() to each button and override each onClick() with its own intent.

这是当您为每个按钮设置一个单独的setOnClickListener()时,并通过它自己的意图覆盖每个onClick()。

In Java class:

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

Advantage: Easy to make on the fly.

优点:容易做苍蝇。

Disadvantage: there will be a lot of anonymous classes which will make readability difficult when reviewing.

缺点:会有很多匿名类,在复习的时候会让可读性变得很困难。

3. Activity wide interface method using the switch statement. (Pro)

This is when you use a switch statement for your buttons within the onClick() method to manage all the Activity's buttons.

这是当您在onClick()方法中使用开关语句来管理所有活动的按钮时。

In Java class:

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

Advantage: Easy button management because all button intents are registered in a single onClick() method

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


For the second part of the question, passing data, please see How do I pass data between Activities in Android application?

对于问题的第二部分,传递数据,请查看我如何在Android应用程序之间传递数据。

#4


31  

When user clicks on the button, directly inside the XML like that:

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

<Button
         android:id="@+id/button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="TextButton"
         android:onClick="buttonClickFunction"/>

Using the attribute android:onClick we declare the method name that has to be present on the parent activity. So I have to create this method inside our activity like that:

使用属性android:onClick我们声明必须出现在父活动上的方法名。所以我必须在我们的活动中创建这个方法:

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

#5


15  

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

#6


8  

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

    This is an explicit intent to start secondscreen activity.

#7


7  

Emmanuel,

以马内利,

I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.

我认为应该在开始活动之前添加额外的信息,否则数据将无法使用,如果您正在使用NextActivity的onCreate方法访问它。

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

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);

#8


6  

From the sending Activity try the following code

从发送活动中尝试以下代码。

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

            }

From the receiving Activity try the following code:

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

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

Then just add the following code to the AndroidManifest.xml file

然后将以下代码添加到AndroidManifest。xml文件

  android:name="packagename.NameOfTheReceivingActivity"
  android:label="Title of the Activity"
  android:parentActivityName="packagename.NameOfSendingActivity"

#9


5  

Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);

#10


3  

The way to start new activities is to broadcast an intent, and there is a specific kind of intent that you can use to pass data from one activity to another. My recommendation is that you check out the Android developer docs related to intents; it's a wealth of info on the subject, and has examples too.

启动新活动的方式是传播意图,并且有一种特定的意图,可以用来将数据从一个活动传递到另一个活动。我的建议是,您可以查看与意图相关的Android开发人员文档;这是一个关于这个主题的丰富的信息,也有一些例子。

#11


3  

You can try this code:

您可以试试下面的代码:

Intent myIntent = new Intent();
FirstActivity.this.SecondActivity(myIntent);

#12


3  

Try this simple method.

试试这个简单的方法。

startActivity(new Intent(MainActivity.this, SecondActivity.class));

#13


2  

Start another activity from this activity and u can pass parameters via Bundle Object also.

从这个活动开始另一个活动,u也可以通过Bundle对象传递参数。

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);

Retrive data in another activity (YourActivity)

在另一个活动(YourActivity)中检索数据

String s = getIntent().getStringExtra("USER_NAME");

#14


2  

Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an[Intent][1]object.

从另一个活动开始活动是android应用程序中非常常见的场景。要启动一个活动,需要一个[意图][1]对象。

How to create Intent Objects?

An intent object takes two parameter in its constructor

intent对象在其构造函数中接受两个参数。

  1. Context
  2. 上下文
  3. Name of the activity to be started.
  4. 要启动的活动的名称。

Example:

So for example,if you have two activities, say HomeActivity and DetailActivity and you want to start DetailActivity from HomeActivity (HomeActivity-->DetailActivity).

例如,如果你有两个活动,比如HomeActivity和DetailActivity,你想从HomeActivity (HomeActivity——>DetailActivity)中启动DetailActivity。

Here is the code snippet which shows how to start DetailActivity from

下面是代码片段,它展示了如何开始进行DetailActivity。

HomeActivity.

HomeActivity。

Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);

And you are done.

和你做。

Coming back to button click part.

回到按钮点击部分。

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

});

#15


1  

Implement the View.OnClickListener interface and override the onClick method.

实现视图。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;
            }

#16


1  

Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.

虽然已经提供了适当的答案,但我在这里是为了在Kotlin语言中寻找答案。这个问题不是关于语言的,所以我添加了代码来完成Kotlin语言的这个任务。

Here is how you do this in Kotlin for andorid

这是你在Kotlin为andorid做这个的方法。

testActivityBtn1.setOnClickListener{
      val intent = Intent(applicationContext,MainActivity::class.java)
      startActivity(intent)

 }

#17


0  

Take Button in xml first.

首先在xml中获取按钮。

  <Button
        android:id="@+id/pre"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@mipmap/ic_launcher"
        android:text="Your Text"
        />

Make listner of button.

使listner按钮。

 pre.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });