多個Activity之間傳值

來源:互聯網
上載者:User

本章將借用一個執行個體,講解如何註冊並啟用一個新的Activity,以及多個Activity之間如何傳值。

下面是主Activity的代碼:

package com.chaoyang.activity;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.text.style.BulletSpan;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Button button =(Button)findViewById(R.id.button);        button.setOnClickListener(new View.OnClickListener() {//給按鈕註冊點擊事件,開啟新的Acticity        @Overridepublic void onClick(View v) {// TODO Auto-generated method stub        //為Intent設定要啟用的組件(將要啟用TheOtherActivity這個Activity)Intent intent =new Intent(MainActivity.this,TheOtherActivity.class);////寫法一 intent.setClass(MainActivity.this, OtherActivity.class);//設定要啟用的組件//寫法二 intent.setComponent(new ComponentName(MainActivity.this, TheOtherActivity.class));//設定要啟用的組件//第一種傳值方式(代碼看起來更加更簡潔)/*intent.putExtra("name", "dinglang");   intent.putExtra("age", 22);   *///第二種傳值方式Bundle bundle =new Bundle();bundle.putString("name", "dinglang");bundle.putInt("age", 22);intent.putExtras(bundle);/* Intent提供了各種常用類型重載後的putExtra()方法,如: putExtra(String name, String value)、 putExtra(String name, long value),在putExtra()方法內部會判斷當前Intent對象內部是否已經存在一個Bundle對象,如果不存在就會建立Bundle對象,以後調用putExtra()方法傳入的值都會存放於該Bundle對象                                            這些其實可以通過看源碼的,內部實現的原理都是一樣的 *///startActivity(intent);//不需要接收組件的傳回值,就可以直接這樣啟用了//需要接收返回結果。注意返回的結果碼startActivityForResult(intent, 100);        }});    }@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {// TODO Auto-generated method stubToast.makeText(this, data.getStringExtra("result"), 1).show();//得到返回結果super.onActivityResult(requestCode, resultCode, data);}}

下面是otherActivity部分代碼:

在相同包下,建立一個類,繼承至Activity這個類,重寫onCreate方法...

package com.chaoyang.activity;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;public class TheOtherActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.other);//設定該Activity所對應的xml布局檔案Intent intent =this.getIntent();//得到啟用她的意圖String name =intent.getStringExtra("name");int age=intent.getExtras().getInt("age");//第二種取值方式TextView textView = (TextView)this.findViewById(R.id.result);textView.setText("姓名:"+ name+"  年齡:"+ age);Button button = (Button)this.findViewById(R.id.close);button.setOnClickListener(new View.OnClickListener() {//返回結果給前面的Activity@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent =new Intent();intent.putExtra("result", "這是處理結果");setResult(20, intent);//設定返回資料finish();//關閉activity}});}}

建立Activity之間,注意要在layout檔案夾中建立一個XML的布局檔案。(建立Android項目時如果選擇了建立Activity,會預設建立一個XML的布局檔案)

下面是布局檔案main.xml:

<?xml version="1.0" encoding="utf-8"?><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:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    />        <Button      android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="開啟OtherActivity"    android:id="@+id/button"    /></LinearLayout>

下面是布局檔案other.xml

<?xml version="1.0" encoding="utf-8"?><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:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="這是OtherActivity"    android:id="@+id/result"    />          <Button      android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:text="關閉Activity"    android:id="@+id/close"    /></LinearLayout>

最後,注意修改項目資訊清單檔。在裡面添加,註冊新的Acticity名稱

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.chaoyang.activity"      android:versionCode="1"      android:versionName="1.0">    <uses-sdk android:minSdkVersion="8" />    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".MainActivity"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <!-- 注意項目資訊清單檔中要加上 --><activity android:name="TheOtherActivity" android:label="the other Activity"/>    </application></manifest>

需要注意的知識點:

使用Intent組件附件資料時候,為Activity之間傳值的兩種寫法。

值得一提的是Bundle類的作用

Bundle類用作攜帶資料,它類似於Map,用於存放key-value名值對形式的值。相對於Map,它提供了各種常用類型的putXxx()/getXxx()方法,如:putString()/getString()和putInt()/getInt(),putXxx()用於往Bundle對象放入資料,getXxx()方法用於從Bundle對象裡擷取資料。Bundle的內部實際上是使用了HashMap<String, Object>類型的變數來存放putXxx()方法放入的值。

還有就是在onActivityResult這個方法中,第一個參數為請求碼,即調用startActivityForResult()傳遞過去的值
,第二個參數為結果碼,結果碼用於標識返回資料來自哪個新Activity。都是起簡單的標識作用的(不要和http協議中的404,200等狀態代碼搞混了),可以根據自己的業務需求填寫,匹配,必要時候可以根據這個去判斷。

這裡就不做深入的講解了。

聯繫我們

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