手机页面转换主要有两种方式:
1. 通过按钮改变Activity的布局文件,即点击按钮时,显示第二个布局文件,这类改变是在同一个Activity中。具体如下:
public void onCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
/* 加载main.xml Layout */
setContentView(R.layout.main);
/* 以findViewById()取得Button对象,并加入onClickListener */
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new Button.OnClickListener()
{
publicvoidonClick(View v)
{
jumpToLayout2();
}
});
}
public void jumpToLayout2()
{
/* 将layout改成mylayout.xml */
setContentView(R.layout.mylayout);
/* 以findViewById()取得Button对象,并加入onClickListener */
Button b2 = (Button) findViewById(R.id.button2);
b2.setOnClickListener(new Button.OnClickListener()
{
publicvoidonClick(View v)
{
jumpToLayout1();
}
});
}
2. 第一种页面转换的方式,只适合布局改变时使用,若需要传递变量就需要采用第二种方法:通过Intent对象实现两个Activity的转换,Bundle对象封装,传递数据。首先在第一个Activity中封装数据:
Intent intent=new Intent();
intent.setClass(MainActivity.this, otherActivity.class);
Bundlebundle=newBundle();
bundle.putDouble("height",height);
bundle.putString("sex", sex);
intent.putExtras(bundle);
startActivity(intent);
然后在第二个Activity中取得数据:
Bundle bundle=this.getIntent().getExtras();
Stringsex = bundle.getString("sex");
double height = bundle.getDouble("height");
注意:当有两个Activity中必须在AndroidManifest.xml里定义一个新的activity。 如下:
<activity
android:name="com.example.ex03_09.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="com.example.ex03_09.otherActivity"> </activity>
第一个activity是首先运行的Activity。