在前面 向应用添加一个新的Activity 里,我们使用 intent 从一个 Activity 跳转到另一个 Activity。其实 intent 在跳转的同时,还可以向目标 Activity 传递参数,这里我们还是以实际例子来说明怎么操作。云鼎娱乐城
MainActivity :
01 |
private Button button; |
02 |
03 |
@Override |
04 |
protected void onCreate(Bundle savedInstanceState) { |
05 |
super .onCreate(savedInstanceState); |
06 |
setContentView(R.layout.activity_main); |
07 |
|
08 |
button = (Button)findViewById(R.id.btn1); |
09 |
button.setOnClickListener( new ButtonListener()); |
10 |
} |
11 |
12 |
class ButtonListener implements OnClickListener{ |
13 |
14 |
@Override |
15 |
public void onClick(View v) { |
16 |
// TODO Auto-generated method stub |
17 |
if ( v.getId() == R.id.btn1){ |
18 |
Intent intent = new Intent(); |
19 |
intent.setClass(MainActivity. this , PaintingActivity. class ); |
20 |
intent.putExtra( "net.nowamagic.nm_painting_v7.Sitemane" , "nowamagic.net" ); |
21 |
intent.putExtra( "net.nowamagic.nm_painting_v7.Years" , "4" ); |
22 |
startActivity(intent); |
23 |
} |
24 |
} |
25 |
|
26 |
} |
在 MainActivity 里,我们向 PaintingActivity 传递了两个参数,一个是字符串 nowamagic.net,一个是整数 4. 那么 PaintingActivity 怎么接收这个参数呢?
PaintingActivity :
01 |
private TextView ptv; |
02 |
03 |
@Override |
04 |
protected void onCreate(Bundle savedInstanceState) { |
05 |
// TODO Auto-generated method stub |
06 |
super .onCreate(savedInstanceState); |
07 |
setContentView(R.layout.painting); |
08 |
|
09 |
ptv = (TextView)findViewById(R.id.ptv); |
10 |
|
11 |
Intent intent = getIntent(); |
12 |
String str = intent.getStringExtra( "net.nowamagic.nm_painting_v7.Sitemane" ); |
13 |
int years = intent.getIntExtra( "net.nowamagic.nm_painting_v7.Years" , 4 ); |
14 |
|
15 |
ptv.setText( "Website " + str + " is " + years + " years old." ); |
16 |
} |
对于不同的数据,需要用不同的函数来接收参数。比如整型用 getIntExtra,字符串用 getStringExtra,这个看看开发文档就清楚了。
程序演示效果如下:
时间: 2024-10-16 03:57:45