Wednesday, December 7, 2011

How to show another activity in android when button click


Using Intent in an Android application to show another activity

In my Android application, I have two activity classes FirstActivity and Second Activity. I have a button on the first one and I want to show the second when it is clicked.


public class FirstActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);  
Button firstButton = (Button)findViewById(R.id.first); 

firstButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
    startActivity(intent);
  }
});
}
}
The second class that should show when the button is clicked:

 public class SecondActivity extends Activity {

 @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Button secondButton = (Button) findViewById(R.id.second);

secondButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    finish();
  }
});
}
}
Important: add this line to your AndroidManifest.xml:
 <activity android:name=".SecondAcitivty" />



No comments:

Post a Comment