Saturday, June 2, 2012

Navigating from one page to another in android


In almost all apps we need to move from 1 page to another. In android we use classes to represent it and often referred as activity. In our project if we have more than 1 class we need to include all the classes in the manifest file using
<activity android:name="Classname"></activity>       
Here, the main class ClassA has got 2 buttons and on clicking the button1 we need to advance to Class1 and on clicking the button2 we need to advance to Class2, and the code snippet is as follows

public class ClassA extends Activity implements OnClickListener 
{
    public void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);
      
       final Button button2 = (Button)this.findViewById(R.id.button2);
       button2.setOnClickListener(new OnClickListener()
        {
        @Override
              public void onClick(View v)
              {
                     navigate();
              }   
        });

    }

       protected void navigate()
        {
              // TODO Auto-generated method stub
              Intent i = new Intent(this,Class2.class);
              startActivity(i);
         }

       @Override
       public void onClick(View v)
         {
              // TODO Auto-generated method stub
              Intent i = new Intent(this,Class1.class);
              startActivity(i);
         }
}

To start a new activity we use Intents. Intents help to combine loosely coupled modules. To use Intent in our code we need to import android.content.Intent class.

No comments:

Post a Comment