我们使用的手机不光是只用到一个应用程序,比如在淘宝界面要付款的时候可能会启动微信付款等,这就相当于在淘宝的Activity中启动了微信的Activity。还比如说当我们注册一个网站是,可能会给自己发送一条短信作为验证,这就是在当前的Activity中启动了短信的Activity。之前对比的MVC设计模式中Controller可以调用另一个Controller中的数据或者跳转等,那么在Android平台中也是可以实现Activity之间的调用的。
程序:
首先做这样一个程序,从一个Activity跳转到另一个Activity中:
关联的布局文件main.xml:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <Button
- android:id="@+id/myButton"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
-
- </LinearLayout>
第一个Activity:
- public class Activity extends ActionBarActivity {
-
-
-
-
- private Button myButton =null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- myButton=(Button)findViewById(R.id.myButton);
-
- myButton.setOnClickListener((android.view.View.OnClickListener) new MyButtonListener());
- }
-
-
- class MyButtonListener implements OnClickListener{
- public void onClick(View v){
-
- Intent intent=new Intent();
- intent.putExtra("testIntent", "123");
- intent.setClass(Activity.this, OtherActivity.class);
- Activity.this.startActivity(intent);
- }
- }
- }
第一个Activity到第二个Activity是通过intent来传送数据的,那么在第二个Activity是如何接收数据的呢?第二个Activity对应的布局文件other.xml中只用一个TextView来盛放数据。
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <TextView
- android:id="@+id/myTextView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
- </LinearLayout>
第二个Activity中接收数据
- public class OtherActivity extends Activity {
- private TextView myTextView=null;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
- setContentView(R.layout.other);
- Intent intent=getIntent();
- String value=intent.getStringExtra("testIntent");
- myTextView=(TextView)findViewById(R.id.myTextView);
- myTextView.setText(value);
- }
- }
当然不要忘记在配置文件中注册第二个Activity:
- <activity android:name=".OtherActivity" android:label="@string/other" />
在一个Activity跳转到另外一个Activity中是通过intent对象来传递的,而一个Intent对象到底能包含多少东西还需要我们自己去实践。