Activity详解二 activity数据传递

首先看效果图:

 

1.Bundle类的作用

  Bundle类用作携带数据,它类似于Map,用于存放key-value名值对形式的值。相对于Map,它提供了各种常用类型的putXxx()/getXxx()方法,如:putString()/getString()和putInt()/getInt(),putXxx()用于往Bundle对象放入数据,getXxx()方法用于从Bundle对象里获取数据。Bundle的内部实际上是使用了HashMap<String, Object>类型的变量来存放putXxx()方法放入的值。简单地说,Bundle就是一个封装好的包,专门用于导入Intent传值的包。

2.为Intent附加数据的两种写法

  第一种写法,用于批量添加数据到Intent:

Intentintent = new Intent();

  Bundle bundle = new Bundle();//该类用作携带数据

  bundle.putString("name","Alice");

  intent.putExtras(bundle);//为意图追加额外的数据,意图原来已经具有的数据不会丢失,但key同名的数据会被替换

  第二种写法:这种写法的作用等价于上面的写法,只不过这种写法是把数据一个个地添加进Intent,这种写法使用起来比较方便,而且只需要编写少量的代码

  Intent intent = new Intent();

  intent.putExtra("name","XXX");

  那么,这两种方法有什么区别呢?

  完全没有区别。当你调用putExtras()方法时,所传入的Bundle会被转化为Intent的键值(别忘了Intent也以键值模式转载数据)。

  那么,现在看看如何将Intent和Bundle取出来。

  方法很简单,直接使用this.getIntent()就可以得到传来的Intent,然后在这个Intent的基础上调用getExtras()就可以得到Bundle。然后这个Bundle你想要什么得到什么就get什么。

  比如String str=bundle.getString("USERNAME"); 就是得到键为“USERNAME”的字符串,int num=bundle.getInt("Number");就是得到键为“Number”的整型。

android中的组件间传递的对象一般实现Parcelable接口,当然也可以使用java的Serializable接口,前者是android专门设计的,效率更高,下面我们就来实现一个Parcelabel。

1. 创建一个类实现Parcelable接口,具体实现如下:

public class ParcelableData implements Parcelable{  

    private String name;  

    private int age;  

    public ParcelableData(){  

        name = "guest";  

        age = 20;  

    }  

    public ParcelableData(Parcel in){  

        //顺序要和writeToParcel写的顺序一样  

        name = in.readString();  

        age = in.readInt();  

    }  

    public String getName(){  

        return name;  

    }  

    public void setName(String name){  

        this.name = name;  

    }  

      

    public int getAge(){  

        return age;  

    }  

    public void setAge(int age) {  

        this.age = age;  

    }  

    @Override  

    public int describeContents() {  

        // TODO Auto-generated method stub  

        return 0;  

    }  

    @Override  

    public void writeToParcel(Parcel dest, int flags) {  

        // TODO Auto-generated method stub  

        dest.writeString(name);  

        dest.writeInt(age);  

    }  

    public static final Parcelable.Creator<ParcelableData> CREATOR = new Parcelable.Creator<ParcelableData>() {  

        public ParcelableData createFromParcel(Parcel in) {  

            return new ParcelableData(in);  

        }  

        public ParcelableData[] newArray(int size) {  

            return new ParcelableData[size];  

        }  

    };  

}  

 

2. 通过下面的方法发送对象。Bundle类也实现了Parcelable接口,一般在android中我们是通过Bundle来封装数据并进行传送的。

Intent intent = new Intent();  

intent.setClass(this, SubActivity.class);  

// 直接添加  

//intent.putExtra("MyData", new ParcelableData());  

  

// 通过Bundle  

Bundle bundle = new Bundle();  

bundle.putString("MyString", "test bundle");  

bundle.putParcelable("MyData", new ParcelableData());  

intent.putExtras(bundle);  

startActivity(intent);  

 

 

3. 下面的接收对象的方法。

//ParcelableData parcelableData = getIntent().getParcelableExtra("MyData");  

Bundle bundle = getIntent().getExtras();  

ParcelableData parcelableData = bundle.getParcelable("MyData");  

String testBundleString = bundle.getString("MyString");  

Log.v("string=", testBundleString);  

Log.v("name=", parcelableData.getName());  

Log.v("age=", ""+parcelableData.getAge());  

 3 DEMO下载

activity代码:

package mm.shandong.com.testbundle;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


import java.util.ArrayList;

import mm.shandong.com.testbundle.entity.Person;

public class TestBundleActivity extends AppCompatActivity {
    EditText editText1;
    EditText editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_bundle);
        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
    }
   ///提交选择的地区,并把地区传递给TestBundleActivity3
    public void submitRegion(View view) {
        EditText editTextRegion = (EditText) findViewById(R.id.editTextRegion);
        Intent intent = new Intent(this, TestBundleActivity3.class);
        String region = editTextRegion.getText().toString();
        if (!TextUtils.isEmpty(region)) {
            intent.putExtra("region", region);
            startActivity(intent);
        } else {
            Toast.makeText(this, "地区不能是空值", Toast.LENGTH_SHORT).show();
        }
    }
    ///把需要计算的两个值都是Integer类型,传入到TestBundleActivity1
    public void calculte(View view) {
        Intent intent = new Intent(this, TestBundleActivity1.class);
        Bundle bundle = new Bundle();
        String first = editText1.getText().toString();
        String second = editText2.getText().toString();
        if (!TextUtils.isEmpty(first) && !TextUtils.isEmpty(second)) {
            bundle.putInt("first", Integer.parseInt(first));
            bundle.putInt("second", Integer.parseInt(second));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            Toast.makeText(this, "数值不能是空", Toast.LENGTH_SHORT).show();
        }
    }
    ///传递Serializable对象到TestBundleActivity2
    public void login(View view) {
        EditText editTextName = (EditText) findViewById(R.id.editTextName);
        EditText editTextCode = (EditText) findViewById(R.id.editTextCode);
        Intent intent = new Intent(this, TestBundleActivity2.class);
        Bundle bundle = new Bundle();
        String name = editTextName.getText().toString();
        String code = editTextCode.getText().toString();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(code)) {
            Person person = new Person();
            person.setName(name);
            person.setCode(code);
            bundle.putSerializable("person", person);
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            Toast.makeText(this, "姓名编号不能是空", Toast.LENGTH_SHORT).show();
        }
    }

}

 

本人微博:honey_11

 

Demo下载
最后,以上例子都来源与安卓无忧,请去应用宝或者豌豆荚下载:例子源码,源码例子文档一网打尽

 

posted on 2016-09-20 11:10  安卓无忧  阅读(602)  评论(0编辑  收藏  举报

导航