天天看點

Activity的建立和使用

Activity:

        1:建立一個類繼承Activity或者它的子類

                public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

Button button=(Button)findViewById(R.id.button1);//擷取按鈕

button.setOnClickListener(new OnClickListener(){//進行監聽

public void onClick(View v) {

// TODO Auto-generated method stub

Intent intent=new Intent(MainActivity.this,DetailActivity.class);//建立Intent對象

startActivity(intent);//啟動Activity

}

});

2:設定布局檔案

                <?xml version="1.0" encoding="utf-8"?>

<LinearLayout 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"

    android:orientation="vertical"

    tools:context=".DetailActivity" >

    <TextView

        android:id="@+id/textView2"

        android:layout_width="129dp"

        android:layout_height="53dp"

        android:text="@string/detail" />

    <Button

        android:id="@+id/button2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/bu" />

</LinearLayout>

      3:重寫繼承類的方法

                   protected void onCreate(Bundle savedInstanceState) {

setContentView(R.layout.detail);//設定布局檔案

Button button=(Button)findViewById(R.id.button2);//擷取關閉按鈕

button.setOnClickListener(new OnClickListener(){

finish();//關閉目前的Activity

          4:在主活動中建立Intent對象并開啟Activity

       setContentView(R.layout.main);

5:在AndroidManifest.xml檔案中配置你所寫類的資訊

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.org.aui"

    android:versionCode="1"

    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="17" />

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.org.aui.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <activity 

            android:icon="@drawable/p1"

            android:name=".DetailActivity"

            android:label="@string/lab"

            >

    </application>

</manifest>

Activity的建立和使用