Thursday, July 10, 2014

Linking between activity1 to activity2 through button in Android



Creating second activity in Android: Before linking between main activity and activity2, we need to create second activity. Procedure to create second activity in Android.

 

Right click on application-> New -> Other

Select the Android activity and click Next.

 

Click finish, activity2 created.

 

You can see two activities in src folder. Add button to first activity and make it link to activity2 by using intents.

XML file of MainActivity:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:text="@string/Button" />

</RelativeLayout>

Java file of MainActivity:


public class MainActivity extends Activity {

    Button b1; //button b1 declared
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 // button1 id for b1
        b1= (Button)findViewById(R.id.button1);
       b1.setOnClickListener(new View.OnClickListener() {
          
           @Override
           public void onClick(View v) {
               // TODO Auto-generated method stub
               Intent i = new Intent(getApplicationContext(), Activity2.class);
               startActivity(i);
              
           }
       });
      
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
 

Snapshots: