Activity 之间的参数传递
在两个Activity之间,可以通过Intent进行参数传递,同时,Intent可以结合包数据Bundle进行打包传输。
Intent
@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){Intent intent=new Intent(MainActivity.this,AnotherActivity.class);intent.putExtra("parameter","start new activity");startActivity(intent);}});}@Overrideprotected 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"));}Bundle
1、 使用Intent.putExtras与Bundle
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {@Overridepublic 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);}});}@Overrideprotected 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
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btnStart).setOnClickListener(new View.OnClickListener() {@Overridepublic 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);}});}@Overrideprotected 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
本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-01/126996.htm