I am trying to open new Activity
by clicking on a button in my OnClickListener
method. How does OnClickListener
method work and what should be done in it to start a new Activity
?
This question is related to
java
android
android-intent
onclicklistener
Use OnClicklistener
or you can use android:onClick="myMethod"
in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod
function in class look like this.
public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}
And in that SecondActivity.class set new layout in contentview.
easy:
launching activity (onclick handler)
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
on the new activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
and add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
//create a variable that contain your button
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
@Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent intent = new Intent(view.getContext(), AnotherActivity.class);
startActivity(intent);
}
});
Source: Stackoverflow.com