Android裡建立的工程一般預設有一個Activity,今天學習如何在這個基礎上再建立一個Activity,並且傳值過去,通過Intent。
/** 建立Activity的要點* 1.一個Activity就是一個類,這個類需要繼承於Activity* 2.需要重寫onCreate方法* 3.每一個Activity都需要在AndroidMainifest.xml檔案當中進行配置* 4.為Activity添加必要的控制項* */
故先建立一個類,名為otherActivity,重寫onCreate()方法,:
建立一個xml布局檔案,內容可以先從系統建立的Activity中複製一下,並添加一個TextView控制項用來顯示Intent傳過來的值:
<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:id="@+id/myTextView" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
在AndroidManifest.xml檔案中進行綁定:
<activity android:name=".otherActivity" android:label="@string/other"></activity>
預設的Activity多了幾行,如下所示,即開機啟動並執行第一個Activity:
<activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
在原先Activity上添加一個Button控制項,並添加一個監聽器。
<Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
// 添加Button監聽器 class MyButtonListener implements android.view.View.OnClickListener{ public void onClick(View v) { // TODO Auto-generated method stub // 產生一個Intent對象 Intent intent = new Intent(); // Intent可以在兩個不同應用程式中的兩個Activity間傳遞資料 intent.putExtra("TestIntent", "123"); intent.setClass(MainActivity.this, otherActivity.class); MainActivity.this.startActivity(intent); } }
把Button控制項與上面的監聽器建立關聯:
// 下面函數的傳回值是View,View是所有Android控制項的父類 Button myButton = (Button)findViewById(R.id.myButton); myButton.setText("第一個Button"); myButton.setOnClickListener(new MyButtonListener());
在otherActivity中擷取並顯示Intent傳的值:
// 擷取Intent Intent intent = getIntent(); String value = intent.getStringExtra("TestIntent"); myTextView = (TextView)findViewById(R.id.myTextView); myTextView.setText(value);
OK!
每天努力一點點,加油!
------------------------------------------------------------------------------------------
作者:龐輝
出處:http://www.cnblogs.com/pang123hui/
本文基於署名 2.5 中國大陸許可協議發布,歡迎轉載,演繹或用於商業目的,但是必須保留本文的署名龐輝(包含連結).