在兩個Activity之間,可以通過Intent進行參數傳遞,同時,Intent可以結合包數據Bundle進行打包傳輸。
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent=new Intent(MainActivity.this,AnotherActivity.class);
intent.putExtra("parameter","start new activity");
startActivity(intent);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
textView=(TextView)findViewById(R.id.textView);
Intent intent=getIntent();
textView.setText(intent.getStringExtra("parameter"));
}
1、 使用Intent.putExtras與Bundle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,AnotherActivity.class);
// intent.putExtra("parameter","start new activity");
Bundle bundle = new Bundle();
bundle.putString("parameter","get bundle data");
bundle.putInt("age",56);
bundle.putString("name1","wgt");
intent.putExtras(bundle);
startActivity(intent);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
textView = (TextView) findViewById(R.id.textView);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
textView.setText(String.format("parameter=%s,age=%d,name1=%s",bundle.getString("parameter"),
bundle.getInt("age"),bundle.getString("name1","leo")));
}
2、 使用Intent.putExtra與Bundle
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,AnotherActivity.class);
// intent.putExtra("parameter","start new activity");
Bundle bundle = new Bundle();
bundle.putString("parameter","get bundle data");
bundle.putInt("age",56);
bundle.putString("name1","wgt");
// intent.putExtras(bundle);
intent.putExtra("bundle",bundle);
startActivity(intent);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
textView = (TextView) findViewById(R.id.textView);
Intent intent = getIntent();
// Bundle bundle = intent.getExtras();
Bundle bundle = intent.getBundleExtra("bundle");
textView.setText(String.format("parameter=%s,age=%d,name1=%s", bundle.getString("parameter"),
bundle.getInt("age"), bundle.getString("name1", "leo")));
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11