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?
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);
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)); } });
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With