筆記內容:
使用Intent實現Activity之間的跳轉
使用Intent實現Activity跳轉時資料的傳遞
知識重點:
實現跳轉
在編寫一個Android應用時,通常需要在幾個Activity之間實現跳轉。如何?跳轉,可以使用Intent對象。
在Eclipse中建立一個Android項目,因為需要實現多個Activity跳轉,所以建立兩個檔案Android_02.java和Android_02_02.java以及main.xml和main_02.xml兩個介面設定檔。通過點擊第一個介面的按鈕跳轉到第二個介面,首先需要修改main.xml檔案。添加如下代碼:
<Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
然後在Android_02.java檔案中中建立一個按鈕對象。並且為按鈕添加監聽器,當按鈕被按下時執行建立Intent對象並實現跳轉。見如下代碼:
mybutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setClass(Android_02.this, Android_02_02.class);//從前一個Activity跳轉到後一個Activity startActivity(intent); } });
簡單分析下代碼,建立了Intent對象,並且使用對象的setClass(Android_02.this, Android_02_02.class)方法實現跳轉,參數1是當前類名,而第2個參數用來設定跳轉的目的。通過點擊按鈕跳轉到Android_02_02這個Activity。
第一個Activity
點擊第一個按鈕後轉到了第二個Activity
資料的傳遞
實現在跳轉過程中,從第一個Activity向第二個Activity傳遞資料是很簡單的。首先在按鈕監聽器中建立Intent對象。和跳轉的代碼完全一樣,只不過在其中多一條代碼,通過對象的putExtra("value", "我是傳遞的內容")方法向第二個Activity傳遞資料,第一個參數是傳遞參數的名稱,第二個參數是參數的內容。這樣就向第二個Activity傳遞了一個參數。如下代碼:
mybutton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.putExtra("value", "我是傳遞的內容");//向Android_02_02傳遞了一個String類型值 intent.setClass(Android_02.this, Android_02_02.class);//從前一個Activity跳轉到後一個Activity startActivity(intent); } });
那麼第二個Activity如何接收這個參數呢。通過www.2cto.com
Intent intent = getIntent();
獲得參數內容。並且將參數的內容顯示作為標籤的內容。如下代碼:
Intent intent = getIntent();//得到上一個Activity傳遞的值 String str=intent.getStringExtra("value"); text.setText(str);//將傳遞的值顯示在標籤上
執行
點擊第一個按鈕後跳轉到第二個Activity且傳遞了參數
作者:JoeBaby_