Articles‎ > ‎Android Articles‎ > ‎

Call intents (classes) in Android simple example code

posted Jan 25, 2011, 1:40 AM by Thiyagaraaj M   [ updated Aug 20, 2011, 4:35 AM ]

First Class XML:(main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Example Application"
    />
 <Button android:id="@+id/btn1" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Click Me"
    />
</LinearLayout>

First Class Java Code:

package com.example.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidExample extends Activity {
    /** Called when the activity is first created. */
   
    Button Btn;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Btn = (Button) findViewById(R.id.btn1);
        Message("Im First Class");
       
        Btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {       
               
                Intent intent = new Intent(AndroidExample.this, Second.class);
                  startActivity(intent);
            }
        });
       
    }
   
    public void Message(String Msg)
    {
        Toast.makeText(AndroidExample.this, Msg.toString(), Toast.LENGTH_SHORT).show();
    }
    }

Second Class XML: (second.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Im Second Class"
    />
</LinearLayout>

Second Class Java Code:(Second.java)

package com.example.android;
import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {
    /** Called when the activity is first created. */
       
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
    }
}

Add to Manifest File:

<activity android:name=".Second"/>
(don't forget this one).

Screen shots

First Intent

Second Intent