Intent的使用
意图,进行页面的跳转,运行时绑定机制,连接两个不同的组件
1、启动一个新的Activity
Intent it1 = new Intent(this, Main2Activity.class);
startActivity(it1);
2、Activity间传值
(1)直接传值:
Intent it2 = new Intent(this, Main2Activity.class);
it2.putExtra("password", "123");
it2.putExtra("name", "小明");
startActivity(it2);
接收:
Intent it_get = getIntent();
team = it_get.getStringExtra("password");
name = it_get.getStringExtra("name");
(2)捆绑传值,使用Bundle:
Intent it2 = new Intent(this, Main2Activity.class);
Bundle bd = new Bundle();
it2.putExtra("password", "123");
it2.putExtra("name", "小明");
it2.putExtras(bd);
startActivity(it2);
接收:
Intent it_get = getIntent();
Bundle bd_get = it_get.getExtras();
team2 = bd_get.getString("team");
name2 = bd_get.getString("password");
Intent最简单的传值
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击2" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(getApplicationContext(), test2.class);
intent.putExtra("name", "001");
startActivity(intent);
}
});
Button btn2=(Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setClass(getApplicationContext(), test2.class);
Bundle bundle = new Bundle();
bundle.putString("name", "123456");
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
test2.java:
public class test2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
TextView tv = (TextView) findViewById(R.id.ItemText);
tv.setText(getIntent().getExtras().getString("name") != null ? getIntent()
.getExtras().getString("name") : getIntent().getStringExtra(
"name"));
}
}