Android中activity和xml的第一個專案
阿新 • • 發佈:2018-12-06
我們使用的手機不光是隻用到一個應用程式,比如在淘寶介面要付款的時候可能會啟動微信付款等,這就相當於在淘寶的Activity中啟動了微信的Activity。還比如說當我們註冊一個網站是,可能會給自己傳送一條簡訊作為驗證,這就是在當前的Activity中啟動了簡訊的Activity。之前對比的MVC設計模式中Controller可以呼叫另一個Controller中的資料或者跳轉等,那麼在Android平臺中也是可以實現Activity之間的呼叫的。
程式:
首先做這樣一個程式,從一個Activity跳轉到另一個Activity中:
關聯的佈局檔案main.xml:
[html] view plain copy
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <Button
- android:id="@+id/myButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
第一個Activity:
[csharp] view plain copy- public class Activity extends ActionBarActivity {
- /**
- * Called when the activity is first created
- */
- //首先獲得點選跳轉的按鈕
- private Button myButton =null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main); //選擇關聯的佈局檔案
- myButton=(Button)findViewById(R.id.myButton); //通過id獲得按鈕
- //通過監聽器把物件捆綁到按鈕上
- myButton.setOnClickListener((android.view.View.OnClickListener) new MyButtonListener());
- }
- //監聽器類
- class MyButtonListener implements OnClickListener{
- public void onClick(View v){
- // 生成一個Intent物件
- Intent intent=new Intent();
- intent.putExtra("testIntent", "123");
- intent.setClass(Activity.this, OtherActivity.class); //設定跳轉的Activity
- Activity.this.startActivity(intent);
- }
- }
- }
第一個Activity到第二個Activity是通過intent來傳送資料的,那麼在第二個Activity是如何接收資料的呢?第二個Activity對應的佈局檔案other.xml中只用一個TextView來盛放資料。
[html] view plain copy- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:id="@+id/myTextView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
第二個Activity中接收資料
[csharp] view plain copy- public class OtherActivity extends Activity {
- private TextView myTextView=null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.other);
- Intent intent=getIntent();
- String value=intent.getStringExtra("testIntent");
- myTextView=(TextView)findViewById(R.id.myTextView);
- myTextView.setText(value);
- }
- }
當然不要忘記在配置檔案中註冊第二個Activity:
[html] view plain copy
- <activity android:name=".OtherActivity" android:label="@string/other" />
在一個Activity跳轉到另外一個Activity中是通過intent物件來傳遞的,而一個Intent物件到底能包含多少東西還需要我們自己去實踐。