1、Android使用意图传递数据之通用方式
1.1 Intent的概念
Intent是一种运行时绑定机制,它能在程序运行的过程中连接两个不同的组件。
1.2 Intent的创建与使用
(1) Intent的创建
Intent intent = new Intent(MainActivity.this,OtherActivity.class);(有多种构造器,这里只是列举一种)
(2)使用Intent传递数据
intent.putExtra("name", "李四");
intent.putExtra("age", 27);
intent.putExtra("address", "广州黄浦区经济开发区");
(3)启动Intent
startActivity(intent);
1.3 代码例子:
MainActivity.java文件:
package com.nxc_boy.myintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button btnTest ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTest = (Button) findViewById(R.id.test);
btnTest.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", 27);
intent.putExtra("address", "广州黄浦区经济开发区");
// 启动意图
startActivity(intent);
}
});
}
}
OtherActivity.java文件
package com.nxc_boy.myintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class OtherActivity extends Activity {
private TextView tv_test;
public OtherActivity() {
// TODO Auto-generated constructor stub
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
tv_test = (TextView) findViewById(R.id.tv_ShowMessage);
Intent intent = getIntent();
int age = intent.getIntExtra("age", 0);
String name = intent.getStringExtra("name");
String address = intent.getStringExtra("address");
tv_test.setText("name: "+ name + "\n" +
"age: " + age + "\n" +
"address: " + address + "\n");
}
}
运行结果如下: