Bundle的用法

来源:互联网 发布:华为quik是什么软件 编辑:程序博客网 时间:2024/06/04 23:20
用Bundle和直接用Intent.putExtra("xx",yy)传递有什么不同


Intent intent = new Intent(); 
intent.putExtra("test_value", "TEST_V"); 



Bundle bundle = new Bundle(); 
bundle.putString("test_value", "TEST_V");
intent.putExtras(bundle); 

  

Bundle bundle = this.getIntent().getExtras();   


举个例子  我现在要从A界面   跳转到B界面或者C界面  
这样的话 我就需要写2个Intent  如果你还要涉及的传值的话 你的Intent就要写两遍添加值的方法 那么 如果我用1个Bundle  直接把值先存里边 然后再存到Intent中 不就更简洁吗?


另外一个例子  如果我现在有  Activity A ,B ,C;
现在我要把值通过A经过B传给C
你怎么传 如果用Intent的话   A-B先写一遍   再在B中都取出来 然后在把值塞到Intent中 再跳到C   累吗?
如果我在A中用了 Bundle 的话  我把Bundle传给B 在B中再转传到C  C就可以直接去了
这样的话 还有一个好处 就是在B中 还可以给Bundle对象添加新的 key - value  同样可以在C中取出来




附:

android Bundle的使用
bundle的认识:



        一种存放字符串和Parcelable类型数据的map类型的容器类,通过存放数据键(key)获取对应的各种类型的值(value),而且必须通过键(key)获取。




bundle的用法:

       Bundle相当于Map类,就是一个映射,用Bundle绑定数据,便于数据处理

        它主要作用于Activity之间的数据传递.


//TestBundle.java

Bundle bundle = new Bundle();//创建一个句柄

bundle.putString("name", nameinfo);//将nameinfo填充入句柄

Intent mIntent = new Intent(TestBundle.this,TestBundle_getvalue.class);

mIntent.putExtras(bundle);

startActivity(mIntent);





//TestBundle_getvalue.java

Bundle bundle = getIntent().getExtras();//获取一个句柄

String nameString=bundle.get("name");//通过key为“name”来获取value即 nameString.



bundle的实例:


第一个Activity发出参数!


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;


public class TestBundle extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}


public boolean onTouchEvent(MotionEvent event) {
Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
Bundle mBundle = new Bundle();
mBundle.putString("Data", "hello, bear");//压入数据
intent.putExtras(mBundle);
startActivity(intent);
finish();
return super.onTouchEvent(event);
}
}


第二个Activity,接收参数


import android.app.Activity;
import android.os.Bundle;


public class Target extends Activity{


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle bundle = getIntent().getExtras();
String data=bundle.getString("Data");//读出数据
setTitle(data);
}
}


另外onCreate(Bundle savedInstanceState) 中的savedInstanceState用于当前activity被切换之前保存临时数据,以便在下次返回时显示之前的数据的。因此在想使用Bundle savedInstanceState保存临时数据,就应该在onCreate(Bundle savedInstanceState)方法中提前写好savedInstanceState!=null时的逻辑。参照理解:http://blog.sina.com.cn/s/blog_652dd96d0100ug6h.html
0 0
原创粉丝点击