我在ListActivity中的构造函数里传递一些变量,通过下面的代码开始活动: startActivity(new Intent (this, viewContacts.class));
现在想使用相似的代码, 把两个字符串传递到构造函数,然后开始执行Intent。怎么实现呢?
为了传递参数,要创建新的意图,放置参数映射:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
为了获得参数值,你必须在同一意图中调用get[type]Extra() 方法
Intent myIntent= getIntent(); // gets the previously created intent
String firstKeyName = intent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String firstKeyName = intent.getStringExtra("firstKeyName"); // will return "SecondKeyValue"
如果参数是整型,要使用getIntExtra()方法。
Intent i = new Intent();
i.putExtra("xxx", "xxx");
i.putExtra("xxx", "xxx");
Intent里可以putExtra(),然后在start的Activity中使用getIntent()可以得到这个Intent。
Intent foo = new Intent(this, viewContacts.class);
foo.putExtra("myFirstKey", "myFirstValue");
foo.putExtra("mySecondKey", "mySecondValue");
startActivity(foo);