Amazon Gift Cards

Saturday, January 3, 2009

Changing Activity in Android

In Android, a new page(html) is a new screen and thus is a new Activity, for example you have an application that has a preferences screen and you want to open that preferences on your application, here is how to do it.

Quick background, here we have 2 Activity classes, Main and Preferences, each activity has its own layout xml. I shall provide only the core code to do this and add a link to the other files that is required for this article.
package com.monmonja.firstDemo;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity implements View.OnClickListener{ 
  private View preferencesBtn;
  public void onCreate(Bundle icicle) { 
    this.preferencesBtn = (Button) this.findViewById(;

  public void onClick(View view) {
    if(view == this.preferencesBtn){
      Intent prefIntent = new Intent(this,Preferences.class);

Quick Explanation
We set up a button to listen to a click event, and on that event we create a new Intent with Intent prefIntent = new Intent(this,Preferences.class);, where we pass the class name of Preferences, then we use this.startActivity(prefIntent); to start our new Activity. You can take a look at our and Preferences.xml to see that the results. When we're on the Preferences Screen you can hit the back button to go back to the Main Screen.

Preferences.xml Chaging Activity In Android
Main.xml Chaging Activity In Android Chaging Activity In Android Chaging Activity In Android

Update History
   Jan 17, 2012 - Visual Update

No comments: