Android學習筆記(十二)——使用意圖傳遞資料的幾種方式

來源:互聯網
上載者:User

標籤:android   intent   資料   textview   adt   

使用意圖傳遞資料的幾種方式


點此擷取完整代碼


我們除了要從活動返回資料,也常常要傳遞資料給活動。對此我們可以使用Intent對象將這些資料傳遞給目標活動。


1、建立一個名為PassingData的項目,在activity_main.xml檔案中添加一個Button:

    <Button        android:id="@+id/btn_SecondActivity"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="Click to go to Second Activity" />

2、在res/layout檔案夾中添加一個新的secondactivity.xml檔案,添加TextView和Button:

    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Welcome to Second Activity" />    <Button        android:id="@+id/btn_MainActivity"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:onClick="onClick"        android:text="Click to return to main activity" />

3、在當前包中建立一個Class,命名為SecondActivity,在SecondActivity.java中添加如下代碼:

package com.example.passingdata;import android.app.Activity;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Toast;public class SecondActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.secondactivity);// 為了獲得通過Intent對象發送的資料,先使用getIntent()方法擷取Intent對象,// 再調用該對象的getStringExtra()方法來獲得使用putExtra()方法設定的字串值Toast.makeText(this, getIntent().getStringExtra("str1"),Toast.LENGTH_SHORT).show();// 同上,對於整數值,調用getIntExtra()方法(注意,如果該名稱沒有儲存值,則會使用預設值,在此為0)Toast.makeText(this,Integer.toString(getIntent().getIntExtra("age1", 0)),Toast.LENGTH_SHORT).show();// 擷取Bundle對象,要使用getExtras()方法:對於字串值,使用getString();對於整數值,使用getInt()Bundle bundle = getIntent().getExtras();Toast.makeText(this, bundle.getString("str2"), Toast.LENGTH_SHORT).show();Toast.makeText(this, Integer.toString(bundle.getInt("age2")),Toast.LENGTH_SHORT).show();}public void onClick(View v) {Intent intent = new Intent();intent.putExtra("age3", 45);// 回傳可以使用setData()方法(上一篇中講過)intent.setData(Uri.parse("Something passed back to main activity"));// 設定Intent和結果碼setResult(RESULT_OK, intent);// 關閉活動finish();}}

4、在AndroidManifest.xml檔案中添加如下代碼:

        <activity            android:name=".SecondActivity"            android:label="Second Activity" >            <intent-filter>                <action android:name="net.zenail.PassingData.SecondActivity" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>

5、在MainActivity.java檔案中添加如下代碼:

public void onClick(View view) {Intent intent = new Intent("net.zenail.PassingData.SecondActivity");// 法一:使用putExtra()方法為Intent對象添加了兩個鍵/值對:String和integer類型intent.putExtra("str1", "This is a string");intent.putExtra("age1", 25);// 法二:建立Bundle對象,向其添加兩個鍵/值對,再使用putExtras添加給Intent對象Bundle extras = new Bundle();extras.putString("str2", "This is another string");extras.putInt("age2", 35);intent.putExtras(extras);// 啟動活動並設定1為請求碼startActivityForResult(intent, 1);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubsuper.onActivityResult(requestCode, resultCode, data);if (requestCode == 1) {if (resultCode == RESULT_OK) {// 用getIntExtra()擷取用putExtra()設定的整數值Toast.makeText(this,Integer.toString(data.getIntExtra("age3", 0)),Toast.LENGTH_SHORT).show();// 用getData()擷取用setData()設定的字串值Toast.makeText(this, data.getData().toString(),Toast.LENGTH_SHORT).show();}}}

6、運行,效果如下:

點擊按鈕:


出現如下畫面:





訊息框消失,點擊按鈕,出現如下畫面:




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.