Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a button to open another activity?

Tags:

java

android

xml

I've added a button to my activity XML file and I can't get it to open my other activity. Can some please tell me step by step on how to do this?

like image 820
BionicDroid Avatar asked Jul 07 '14 12:07

BionicDroid


People also ask

How do I use intent to launch a new activity?

The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo. class); startActivity(i);


2 Answers

A. Make sure your other activity is declared in manifest:

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

All activities must be declared in manifest, even if they do not have an intent filter assigned to them.


B. In your MainActivity do something like this:

Button btn = (Button)findViewById(R.id.open_activity_button);      btn.setOnClickListener(new View.OnClickListener() {                  @Override         public void onClick(View v) {             startActivity(new Intent(MainActivity.this, MyOtherActivity.class));         } }); 
like image 81
Gilad Haimov Avatar answered Sep 28 '22 18:09

Gilad Haimov


Using an OnClickListener

Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

Button yourButton = (Button) findViewById(R.id.your_buttons_id);  yourButton.setOnClickListener(new OnClickListener(){     public void onClick(View v){                                 startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));     } }); 

This is probably most developers preferred method. However, there is a common alternative.

Using onClick in XML

Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

public void yourMethodName(View v){     startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class)); } 

Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

References;

  • Starting Another Activity (Official API Guide)
like image 45
Rudi Kershaw Avatar answered Sep 28 '22 18:09

Rudi Kershaw