您的位置:首页 > 移动开发 > Android开发

【Android】使用Intent实现数据传递

2013-11-05 14:44 633 查看
这个例子是根据老罗的Android视频编写的。

在上篇blog中提到了使用Intent来实现Activity之间的跳转,实际上在跳转时还需要传递信息,例如我们在手机上点击某个联系人的名字就转到那个人的页面。

1.通用方式

1.首先创建另外一个Activity,新建类,在Manifest中写入。为了后面显示信息,要添加一个TextView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

<TextView
android:id="@+id/msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>


2.在Main中添加一个按钮,在该按钮的点击事件处理中新建Intent,并附加消息。

button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,OtherActivity.class);
//在意图中传递数据
intent.putExtra("name", "张三");
intent.putExtra("age", 23);
intent.putExtra("address", "北京");
//启动意图
startActivity(intent);
}
});


3.在Other中添加显示信息的代码,将信息显示到之前创建的TextView中。

textView = (TextView) this.findViewById(R.id.msg);

Intent intent = getIntent();
int age = intent.getIntExtra("age", 0);
String name = intent.getStringExtra("name");
String address = intent.getStringExtra("address");

textView.setText("age--->>" + age + "\n" + "name-->>" + name + "\n"
+ "address-->>" + address);


不要忘了前面加一句:

setContentView(R.layout.other);


这时候就可以测试一下了。 

2.使用静态变量 

跟上面代码类似,只需在Main和Other两个Activity中做一些更改。

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//声明一个意图
Intent intent = new Intent();
intent.setClass(MainActivity.this, OtherActivity.class);
OtherActivity.age = 23;
OtherActivity.name = "jack";
startActivity(intent);
}
});


public static String name;
public static int age;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
textView = (TextView) this.findViewById(R.id.msg);
textView.setText("--name->>" + name + "\n" + "--age->>" + age);
}


上面的代码改动就是Intent的生成方式,以及在Other中声明了几个静态变量。

3.使用静态变量

同样只需要改动那两个部分:

button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
String name = "jack";
clipboardManager.setText(name);

Intent intent = new Intent(MainActivity.this,OtherActivity.class);
startActivity(intent);
}
});


textView = (TextView)this.findViewById(R.id.msg);
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
String msgString = clipboardManager.getText().toString();
textView.setText(msgString);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android