setContentView的应用
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
??? android:orientation="vertical"
??? android:layout_width="fill_parent"
??? android:layout_height="fill_parent"
??? >
<TextView?
??? android:layout_width="fill_parent"
??? android:layout_height="wrap_content"
??? android:text="欢迎来到魏祝林的博客"
??? />
<Button
??? android:id="@+id/bt1"
??? android:layout_width="wrap_content"
??? android:layout_height="wrap_content"
??? android:text="点击进入Layout2"
/>
</LinearLayout>
其次我们在main.xml同一目录新建一个为mylayout.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
??? android:orientation="vertical"
??? android:layout_width="fill_parent"
??? android:layout_height="fill_parent"
??? android:background="#ffffffff"
??? >
<TextView?
??? android:layout_width="fill_parent"
??? android:layout_height="wrap_content"
??? android:text="Welcome to Mr Wei's blog"
??? />
<Button
??? android:id="@+id/bt2"
??? android:layout_width="wrap_content"
??? android:layout_height="wrap_content"
??? android:text="点击进入Layout1"
/>
</LinearLayout>
最后是我们的核心程序setContentViewDemo.java
package com.android.setContentViewDemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class setContentViewDemo extends Activity {
??? public void onCreate(Bundle savedInstanceState) {
??? ??? super.onCreate(savedInstanceState);
??? ??? // 载入main.xml Layout
??? ??? setContentView(R.layout.main);
??? ??? // 以findViewById()取得Button对象并添加事件onClickLisener
??? ??? Button bt1 = (Button) findViewById(R.id.bt1);
??? ??? bt1.setOnClickListener(new Button.OnClickListener() {
??? ??? ??? public void onClick(View v) {
??? ??? ??? ??? goToLayout2();
??? ??? ??? }
??? ??? });
??? }
??? // 将layout由main.xml切换成mylayout.xml
??? public void goToLayout2() {
??? ??? // 将layout改成mylayout
??? ??? setContentView(R.layout.mylayout);
??? ??? Button b2 = (Button) findViewById(R.id.bt2);
??? ??? b2.setOnClickListener(new Button.OnClickListener() {
??? ??? ??? public void onClick(View v) {
??? ??? ??? ??? goToLayout1();
??? ??? ??? }
??? ??? });
??? }
??? // 将layout由mylayout.xml切换成main.xml
??? public void goToLayout1() {
??? ??? setContentView(R.layout.main);
??? ??? Button bt1 = (Button) findViewById(R.id.bt1);
??? ??? bt1.setOnClickListener(new Button.OnClickListener() {
??? ??? ??? public void onClick(View v) {
??? ??? ??? ??? goToLayout2();
??? ??? ??? }
??? ??? });
??? }
}
最后执行之!,这一节就到此结束~