Android開發中使用Bundle數據傳值

Bundle是Android開發中的一個類,用於Activity之間傳輸數據用,Bundle就是一個專門用於導入Intent傳值的包。

1.MainActivity.xml 傳輸數據(4步)

//設置Button點擊事件,傳輸數據進入下一個頁面
btn01.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();//1.實例化一個Intent,得到Intent對象
        intent.setClass(MainActivity.this, Change.class);//當前頁面到下一個頁面
        Bundle bundle = new Bundle();//2.實例化一個Bundle,得到Bundle對象
        sninfo.setSnlist(snlists);//設置數據
        saomiaostr = new Gson().toJson(sninfo);//獲取包裹裏的內容
        bundle.putString("saomiao", saomiaostr);//3.把數據保存到Bundle裏
        intent.putExtra("Message", bundle);//4.把Bundle放入Intent裏,通過Intent將Bundle傳到另一個Activity裏
        startActivityForResult(intent, 0);
    }
});

2.Change.xml 設置接收數據(3步)

Intent intent = getIntent();//1.獲取Bundle傳遞的對象
Bundle bundle = intent.getBundleExtra("Message");//2.從intent取出bundle
yisaosnstr = bundle.getString("saomiao");//3.找到自己的包裹
sninfo = new Gson().fromJson(yisaosnstr, Sninfo.class);//3.獲得包裹裏的信息
snlistList = sninfo.getSnlist();//需要什麼類型找什麼類型
int i = 0;
for (Snlist s : snlistList) {
    i = i + 1;
    sn = sn + i + ". " + s.getSku() + " : " + s.getSn() + "\n";
}

3.Change.xml 返回數據(5步)

//設置Button點擊事件,返回數據進入上一個頁面
confirmbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intentnew = new Intent();//1.實例化一個Intent,得到Intent對象
        intentnew.setClass(Change.this, MainActivity.class);//當前頁面到上一個頁面
        Bundle bundlenew = new Bundle();2.實例化一個Bundle,得到Bundle對象
        sninfo.setSnlist(snlistList);//設置數據
        String aftersaomiaostr = new Gson().toJson(sninfo);//獲取包裹裏的內容
        bundlenew.putString("aftershanchu", aftersaomiaostr);3.把數據保存到Bundle裏
        intentnew.putExtra("afterxiugai", bundlenew);4.把Bundle放入Intent裏,通過Intent將Bundle傳到另一個Activity裏
        Change.this.setResult(1, intentnew);
        Change.this.finish();//5.關閉頁面
    }
});

4.MainActivity.xml 接收返回數據(2步)

//接收返回數據
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);//1.獲取包裹
    switch (requestCode) {
        case 0:
            switch (resultCode) {
                case 1://2.獲取信息
                    Bundle bundle = data.getBundleExtra("afterxiugai");
                    shanchuhoustr = bundle.getString("aftershanchu");
                    xiugaihousninfo = new Gson().fromJson(shanchuhoustr, Sninfo.class);
                    }
            }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章