不同Activity的数据传递(Bundle的使用)
新建一个继承Activity类的BundleOneActivity,并设置布局文件为:bundleone.xml。
新建一个继承Activity类的BundleTwoActivity,并设置布局文件为:bundletwo.xml。
在bundleone.xml和bundletwo.xml中都添加一个TextView和Button组件
<TextView android:id="@+id/bundleone_tv01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/go_to_bundletwoactivity" android:textSize="24sp" />
<Button android:id="@+id/bundleone_btn01" style="@android:style/Widget.Button.Inset" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/go_to_bundletwoactivity" android:textSize="24sp" /> |
修改完布局文件后,在BundleOneActivity类中得到TextView和Button的实例化对象。并添加Button的点击事件。
package lyx.feng.simpletextdemo; ...... publicclass BundleOneActivity extends Activity implements OnClickListener { private TextView tv = null; private Button btn = null;
@Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.bundleone); this.tv = (TextView) super.findViewById(R.id.bundleone_tv01); this.btn = (Button) super.findViewById(R.id.bundleone_btn01); this.tv.setText("这是要传递的参数"); this.btn.setOnClickListener(this); }
@Override publicvoid onClick(View v) {
} }
|
接下来的操作主要是在onClick(View v)方法中进行。要在Activity传递数据,只需要将要传递的数据添加到Intent对象中即可。这里使用Bundle进行数据的封装。
具体代码:
Intent intent = new Intent(this, BundleTwoActivity.class); Bundle bundle = new Bundle(); bundle.putString("info", tv.getText().toString()); intent.putExtras(bundle); startActivity(intent); |
而后在BundleTwoActivity类中对传递过来的数据进行接收。
package lyx.feng.simpletextdemo; ....... publicclass BundleTwoActivity extends Activity implements OnClickListener { private TextView tv = null; private Button btn = null;
@Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.bundletwo); this.tv = (TextView) super.findViewById(R.id.bundletwo_tv01); this.btn = (Button) super.findViewById(R.id.bundletwo_btn01); this.btn.setOnClickListener(this);
Bundle bundle = getIntent().getExtras(); if (bundle != null) { tv.setText("传递的数据是:"); tv.append(bundle.getString("info")); }
}
@Override publicvoid onClick(View v) {
} }
|
运行效果:
点击按钮后:
如果要在BundleTwoActivity返回数据到BundleOneActivity,则需要在BundleTwoActivity的onClick()方法操作返回数据的代码。
Intent intent = new Intent(); intent.putExtra("temp", "这是返回的数据!"); setResult(RESULT_OK, intent); this.finish(); |
只是在BundleOneActivity进行跳转的时候选用:startActivityForResult()方法。
而后覆写Activity的onActivityResult()方法.
具体的代码:
@Override protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 1: if (resultCode!=RESULT_OK) { return; } Toast.makeText(this, "返回的数据:" + data.getExtras().getString("temp"), Toast.LENGTH_SHORT).show(); break; } } |
在BundleOneActivity点击返回按钮后: