Android 使用Intent實現Activity跳轉和資料傳遞

來源:互聯網
上載者:User

筆記內容:
使用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_

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.