Android之Bundle傳遞資料詳解與執行個體及Bundle與SharedPreferences的區別

來源:互聯網
上載者:User

 

效果如下:

 

初始介面

輸入資訊

“確定”以後

一、API文檔說明

  1.介紹

    用於不同Activity之間的資料傳遞

  1.重要方法

    clear():清除此Bundle映射中的所有儲存的資料。

    clone():複製當前Bundle

    containsKey(String key):返回指定key的值

    getString(String key):返回指定key的字元

    hasFileDescriptors():指示是否包含任何捆綁打包檔案描述符

    isEmpty():如果這個捆綁映射為空白,則返回true

    putString(String key, String value):插入一個給定key的字串值

    readFromParcel(Parcel parcel):讀取這個parcel的內容

    remove(String key):移除指定key的值

    writeToParcel(Parcel parcel, int flags):寫入這個parcel的內容

 

二、執行個體

  

public class BundleDemo extends Activity {
 private EditText etName;
 Button btn;

 /*
  * (non-Javadoc)
  * 
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  setContentView(R.layout.bundle);

  etName = (EditText) findViewById(R.id.etname);
  btn = (Button) findViewById(R.id.btn);
  btn.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    String info = etName.getText().toString();
    Bundle bundle = new Bundle();

  //儲存輸入的資訊
    bundle.putString("name", info);
    Intent intent=new Intent(BundleDemo.this,BundleDemo1.class);
   intent.putExtras(bundle);
   finish();
   startActivity(intent);
   }
  });

 }

}

 

public class BundleDemo1 extends Activity {
private TextView etName;
 /* (non-Javadoc)
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  
  setContentView(R.layout.b1);
  
  etName=(TextView)findViewById(R.id.txtname);
  Bundle b=getIntent().getExtras();
  //擷取Bundle的資訊
  String info=b.getString("name");
  etName.setText("您的姓名:"+info);
 }

}

 

三、與SharedPreferences的區別

  SharedPreferences是簡單的儲存持久化的設定,就像使用者每次開啟應用程式時的首頁,它只是一些簡單的索引值對來操作。它將資料儲存在一個xml檔案中

  Bundle是將資料傳遞到另一個上下文中或儲存或回複你自己狀態的資料存放區方式。它的資料不是持久化狀態。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.