作者:刘昊昱
博客:http://blog.csdn.net/liuhaoyutz
一个Activity可以启动另外一个Activity,以实现比较复杂的功能,我们来看一个例子,其运行效果如下图所示:
主布局文件main.xml如下所示:
<?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="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20dp" android:text="启动另外一个Activity示例:" /> <Button android:id="@+id/button" android:text="启动" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
主Activity内容如下所示:
package com.liuhaoyu; 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 { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button=(Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } }
点击按钮时,通过Intent启动另外一个Activity,这里是SecondActivity,其内容如下:
package com.liuhaoyu; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second); } }
SecondActivity的布局文件内容如下:
<?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" > <TextView android:id="@+id/textView" android:text="这是被调用的Activity!" android:textSize="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content" />" </LinearLayout>
本程序中定义了两个Activity,需要在AndroidManifest.xml文件中声明SecondActivity:
<activity android:icon="@drawable/ic_launcher" android:name=".SecondActivity" android:label="Activity" android:theme="@android:style/Theme.Dialog" > </activity>