Bundle usage

The use of android bundle

Bundle awareness:

        A container class of map type that stores string and Parcelable type data, and obtains corresponding values ​​of various types by storing data keys (keys), and must be obtained through keys (keys).

 

Usage of bundle:

       Bundle is equivalent to the Map class, which is a mapping. Bundle data is bound to facilitate data processing.

        It is mainly used for data transfer between Activities. 

 

//TestBundle.Java

Bundle bundle = new Bundle();//Create a handle

bundle.putString("name", nameinfo);//fill nameinfo into the handle

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

mIntent.putExtras(bundle);

startActivity (mIntent);

 

//TestBundle_getvalue.java

Bundle bundle = getIntent().getExtras();//Get a handle

String nameString=bundle.get("name");//Get value by key as "name", namely nameString.

/*

* Perform related operations

*/

 

Examples of bundles:

      The first Activity emits parameters!

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); 

}

 

In addition, the savedInstanceState in onCreate(Bundle savedInstanceState) is used to save temporary data before the current activity is switched, so that the previous data can be displayed the next time it returns. Therefore, if you want to use Bundle savedInstanceState to save temporary data, you should write savedInstanceState in advance in the onCreate(Bundle savedInstanceState) method! Logic when =null. Refer to understanding: http://blog.sina.com.cn/s/blog_652dd96d0100ug6h.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326785787&siteId=291194637
Recommended