1. 程式人生 > >android中使用startActivityForResult回傳資料(詳解)

android中使用startActivityForResult回傳資料(詳解)

在使用新浪微博APP時,能發現在微博釋出介面進入相簿選擇圖片後,會回到微博釋出頁面並帶回了圖片選擇頁面的圖片資訊。由於這種需求十分常見,因此,Android提供了一個startActivityForResult()方法,來實現回傳資料。

要求:頁面1跳轉到頁面2,頁面2再返回頁面1同時返回資料

頁面1新增如下程式碼:

 Intent intent = new Intent();
   intent.setClass(頁面1.this, 頁面2.class);
   Bundle bundle = new Bundle();
   intent.putExtras(bundle);//將Bundle新增到Intent,也可以在Bundle中新增相應資料傳遞給下個頁面,例如:bundle.putString("abc", "bbb");
startActivityForResult(intent, 0);// 跳轉並要求返回值,0代表請求值(可以隨便寫)

頁面2接收資料新增程式碼如下:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
bundle.putString("aaa", "back");//新增要返回給頁面1的資料
intent.putExtras(bundle);
this.setResult(Activity.RESULT_OK, intent);//返回頁面1
this.finish();

頁面1接收返回資料:(需要重寫onActivityResult)

onActivityResult()方法裡面的三個引數  第一個引數requestCode,表示再啟動Acitivity是傳遞的請求碼  第二個引數resultCode,表示再返回資料時傳入結果碼 第三個參data,表示攜帶返回資料的Intent

複製程式碼
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
            Bundle bundle 
= data.getExtras(); gameView.backString = bundle.getString("aaa"); Toast.makeText(this, backString, Toast.LENGTH_SHORT).show(); } }
複製程式碼

我用一個具體的案例更好的幫助大家理解下startActivityForResult()方法

首先看一下效果圖

                                                                   

                       

執行程式,在主介面中分別單機“主人購買裝備” “小寶寶購買裝備” 按鈕  , 會跳轉至裝備展示介面(第二幅圖),裝備購買成功後,會看到第三幅圖片。

首先建立一個ItemInfo的類  用於封裝裝備資訊。具體程式碼如下:

public class ItemInfo implements Serializable {
    private String name;
    private int acctack;
    private int life;
    private int speed;

    public ItemInfo(String name, int acctack, int life, int speed) {
        this.name = name;
        this.acctack = acctack;
        this.life = life;
        this.speed = speed;
    }

    public String getName() {
        return name;
    }

    public int getAcctack() {
        return acctack;
    }

    public int getLife() {
        return life;
    }

    public int getSpeed() {
        return speed;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAcctack(int acctack) {
        this.acctack = acctack;
    }

    public void setLife(int life) {
        this.life = life;
    }

    public void setSpeed(int speed) {
        this.speed = speed;
    }

    @Override
    public String toString() {
        return "ItemInfo{" +
                "name='" + name + '\'' +
                ", acctack=" + acctack +
                ", life=" + life +
                ", speed=" + speed +
                '}';
    }
}

需要注意的是Intent除了傳遞基本資料型別之外,也能傳遞Serializable或Parcelable型別的資料,為了方便資料傳遞,在這裡讓ItemInfo類實現Serializable介面

建立一個ShopActivity是用來展示裝備資訊的,當單擊ShopActivity的裝備時,會呼叫MainActicity並將裝備資訊回撥給MainActivity,ShopActivity的具體程式碼如下:

public class ShopActivity extends Activity implements View.OnClickListener{

    private ItemInfo mItemInfo;
    private TextView mLifeTv;
    private TextView mNameTv;
    private TextView mSpeedTv;
    private TextView mAttackTv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        mItemInfo = new ItemInfo("金劍",100,20,20);
        findViewById(R.id.rl).setOnClickListener(this);
        initWidget();
    }

    private void initWidget() {
        mLifeTv = (TextView) findViewById(R.id.tv_life);
        mNameTv = (TextView) findViewById(R.id.tv_name);
        mSpeedTv = (TextView) findViewById(R.id.tv_speed);
        mAttackTv = (TextView) findViewById(R.id.tv_attack);
        mLifeTv.setText("生命值"+ mItemInfo.getLife());
        mNameTv.setText(mItemInfo.getName()+"");
        mSpeedTv.setText("敏捷度"+ mItemInfo.getSpeed());
        mAttackTv.setText("攻擊力"+mItemInfo.getAcctack());
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.rl:
                Intent intent = new Intent();
                intent.putExtra("equipment",mItemInfo);
                setResult(1,intent);
                finish();
                break;
        }

    }
}

MainActivity主要用於響應按鈕的點選事件,並將返回的裝備資訊顯示到指定的控制元件中,具體程式碼如下:
public class MainActivity extends AppCompatActivity {

    private TextView mLifeTv;
    private TextView mAttackTv;
    private TextView mSpeedTv;
    private ProgressBar mProgressBar1;
    private ProgressBar mProgressBar2;
    private ProgressBar mProgressBar3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initWidget();
    }

    private void initWidget() {
        mLifeTv = (TextView) findViewById(R.id.tv_life_progress);
        mAttackTv = (TextView) findViewById(R.id.tv_attack_progress);
        mSpeedTv = (TextView) findViewById(R.id.tv_speed_progress);
        mProgressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
        mProgressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
        mProgressBar3 = (ProgressBar) findViewById(R.id.progressBar3);
        mProgressBar1.setMax(100);              // 設定最大值為100
        mProgressBar2.setMax(100);
        mProgressBar3.setMax(100);
    }
    public void click(View view){
        Intent intent = new Intent(this,ShopActivity.class);
        startActivityForResult(intent,1);  // 返回請求結果返回值為1
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null){
            //判斷結果碼是否等於1 , 等於1為寶寶新增裝備
            if (resultCode == 1){
                if (requestCode == 1){
                            ItemInfo info = (ItemInfo) data.getSerializableExtra("equipment");
                    // 更新ProgressBar的值
                    updatePogress(info);
                }
            }
        }
    }

    private void updatePogress(ItemInfo info) {
        int progress1 = mProgressBar1.getProgress();
        int progress2 = mProgressBar2.getProgress();
        int progress3 = mProgressBar3.getProgress();
        mProgressBar1.setProgress(progress1+info.getLife());
        mProgressBar2.setProgress(progress2+info.getAcctack());
        mProgressBar3.setProgress(progress3+info.getSpeed());
        mLifeTv.setText(mProgressBar1.getProgress()+"");
        mAttackTv.setText(mProgressBar2.getProgress()+"");
        mSpeedTv.setText(mProgressBar3.getProgress()+"");

    }
}

xml的程式碼如下:

activity_main.xml如下:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/pet_imgv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="30dp"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/pet_dialog_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="25dp"
        android:gravity="center_horizontal"
        android:text="主人,快給小寶寶買裝備吧"/>

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="25dp">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="生命值"
                android:textColor="@android:color/black"
                android:textSize="14sp"/>

            <ProgressBar
                android:id="@+id/progressBar1"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="2"/>

            <TextView
                android:id="@+id/tv_life_progress"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="0"
                android:textColor="#000000"/>
        </TableRow>

    </TableLayout>


    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="25dp">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="攻擊力"
                android:textColor="@android:color/black"
                android:textSize="14sp"/>

            <ProgressBar
                android:id="@+id/progressBar2"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="2"/>

            <TextView
                android:id="@+id/tv_attack_progress"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="0"
                android:textColor="#000000"/>
        </TableRow>

    </TableLayout>


    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="25dp">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="敏捷"
                android:textColor="@android:color/black"
                android:textSize="14sp"/>

            <ProgressBar
                android:id="@+id/progressBar3"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="2"/>

            <TextView
                android:id="@+id/tv_speed_progress"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="0"
                android:textColor="#000000"/>
        </TableRow>

    </TableLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:layout_marginTop="20dp">

        <Button
            android:id="@+id/btn_baby"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="click"
            android:text="小寶寶購買裝備"
            android:textSize="14sp"/>

    </RelativeLayout>


</LinearLayout>
裝備介面的xml如下:activity_shop.xml 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/rl"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
    >

    <View
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="@android:drawable/ic_menu_info_details"/>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="60dp"
        android:text="商品名稱"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_life"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="生命值"
            android:textSize="13sp"/>

        <TextView
            android:id="@+id/tv_attack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="攻擊力"
            android:textSize="13sp"/>

        <TextView
            android:id="@+id/tv_speed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="速度"
            android:textSize="13sp"/>

    </LinearLayout>


</RelativeLayout>


相關推薦

android使用startActivityForResult回傳資料

在使用新浪微博APP時,能發現在微博釋出介面進入相簿選擇圖片後,會回到微博釋出頁面並帶回了圖片選擇頁面的圖片資訊。由於這種需求十分常見,因此,Android提供了一個startActivityForResult()方法,來實現回傳資料。 要求:頁面1跳轉到頁面2,頁面2

使用Docker實現MySql資料庫在容器的主從配置

使用Docker容器搭建MySql主從複製 關於如何建立映象,我的部落格中有詳細的步驟文件 檢視容器ip命令為docker inspect 96fd[id前四位] Master_mysql_ip_172.17.0.4 slave_mysql_ip_172.17.0.5 1.docker上面尋

python介面自動化三十七-封裝與呼叫--讀取excel 資料

簡介   在進行軟體介面測試或設計自動化測試框架時,一個不比可避免的過程就是: 引數化,在利用python進行自動化測試開發時,通常會使用excel來做資料管理,利用xlrd、xlwt開源包來讀寫excel。例如:當我們登入的賬號有多個的時候,我們一般用 excel 存放測試資料,本篇文章介紹,pytho

Nmap在實戰的高階用法

@[toc] # Nmap在實戰中的高階用法(詳解) Nmap提供了四項基本功能(主機發現、埠掃描、服務與版本偵測、OS偵測)及豐富的指令碼庫。Nmap既能應用於簡單的網路資訊掃描,也能用在高階、複雜、特定的環境中:例如掃描網際網路上大量的主機;繞開防火牆/IDS/IPS;掃描Web站點;掃描路由器等等。

android使用startActivityForResult回傳資料

目的: A.java 是主介面,B.java 是子功能模組,要從A啟動B,B幹完活之後把結果彙報給A 先看 A.java 的相關程式碼 //-- A.java --// /*  * 要做兩件事情,第一是用 startActivityForResult() 啟動B,其次是回

android開發學習 ------- 【轉】 android的單例模式

lan post tail -- and 使用 href details android開發 https://blog.csdn.net/u011418943/article/details/60139644 這篇文章 前因後果 都說出來了 ,值得學習。 htt

Android Studio匯入SlidingMenu

AS中匯入GitHub開源專案SlidingMenu總結,我開始AS匯入SlidingMenu的時候也百度了很多文章,寫的都不是很詳細,所以匯入成功後,寫了這篇文章,希望對想用AndroidStudio匯入SlidingMenu的小夥伴有所啟發。 先上最終效果圖動畫 2

Android聯絡人和通話記錄2

  在文章Android中聯絡人和通話記錄詳解(1)中對通話記錄進行了分析,本章將對聯絡人的資料庫表、欄位以及Insert,Query,Delelte,Update四大基本資料操作進行分析。   與聯

Android聯絡人和通話記錄(聯絡人的增刪改查)3

    在上一章 Android中聯絡人和通話記錄詳解(2)中分析了聯絡人相關的表和欄位,在這一章中將分析聯絡人相關的基本資料操作(Insert,Query,Update,Delete)。    1.新增(Insert)      從contacts,data,mimety

Android 使用MediaRecorder進行錄影視訊錄製

在這裡給出自己的一個測試DEMO,裡面註釋很詳細。簡單的視訊錄製功能. package com.demo; import java.io.IOException; import android.app.Activity; import android

Android的介面回撥,回撥機制:以Activity和Adapter傳遞資料為例。

首先解決啥是回撥: 我覺得這個例子比較好:某天,我打電話向你請教問題,當然是個難題,你一時想不出解決方法,我又不能拿著電話在那裡傻等,於是我們約定:等你想出辦法後打手機通知我,這樣,我就掛掉電話辦其它事情去了。過了XX分鐘,我的手機響了,你興高采烈的說問題已經搞定,應該

專案執行緒原來是這麼使用的

實現執行緒同步的幾種方式 1.同步方法 即有synchronized關鍵字修飾的方法。 由於java的每個物件都有一個內建鎖,當用此關鍵字修飾方法時, 內建鎖會保護整個方法。在呼叫該方法前,需要獲得內建鎖,否則就處於阻塞狀態。 程式碼如: public synchro

在伺服器安裝jdk1.8版本的安裝,原來這麼簡單

因為在烏班圖的系統中由於只能註冊普通的使用者,不能註冊root使用者。 所以需要先把jdk-8u11-linux-x64.tar.gz的安裝包拷貝到普通使用者的許可權中去。 我們可以使用WinSCP視覺化工具直接對壓縮包進行拖拽到指定的目錄下,也可以使用Xshell工具使用命令列對檔

java的變數原來有這些

1 初識java a 開啟MyEclipse b 開啟File->new->java project (建立專案) c 在project name 起名 (給專案命名) d 開啟File->new->class name起個名字 最好叫Test (建立類並命名) e

原來mysql在伺服器,虛機是這麼使用的

1.以root身份登入到MySQL伺服器中。 $ mysql -u root -p 當驗證提示出現的時候,輸入MySQL的root帳號的密碼。 2.建立一個MySQL使用者 使用如下命令建立一個使用者名稱和密碼分 為”username”和”userpassword”的使用者。

js入門 關於js屬性及其資料型別

1. js的本質就是處理資料。資料來自於後臺的資料庫。 所以變數就起到一個臨時儲存資料的作用。 ECMAScript制定了js的資料型別。 資料型別有哪些? 1. 字串   String 2. 數字    Number

Spark資料過濾、自定義分割槽、Shuffer調優 經典案例

案例: 根據學科取得最受歡迎的老師的前兩名 這個是資料 http://bigdata.edu360.cn/zhangsan http://bigdata.edu360.cn/zhangsan http://bigdata.edu360.cn/lisi http:

vue localStorage的使用方法

vue中實現本地儲存的方法:localStorage,在HTML5中,新加入了一個localStorage特性,這個特性主要是用來作為本地儲存來使用的,解決了cookie儲存空間不足的問題(cookie中每條cookie的儲存空間為4k),localStorage中一般瀏覽器支援的是5M大小,這個在

原來資料庫的模糊查詢,分組,聯合查詢是這麼使用的

1 模糊查詢 like關鍵字 萬用字元 % 任意長度的任意字串 _ 代表任意一個字元 [1-6] 代表1到6之間的一個字元 [^0-5] 代表不是0到5之間的一個字元 between 值1 and 值2 select * from 表名 where 列

實際開發時間戳原來是這麼使用的

在改客戶需求時,需要獲得當時的時間戳顯示的時間, 但是在前臺報錯Cannot convert value ‘2018-07-02 17:14:20.000000’ from column 28 to TIMESTAM 說明是時間戳轉換時轉換異常報錯。 在查詢時把