How Do I Get A Button To Open Another Activity In Android Studio
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));
}
No comments:
Post a Comment