【从头学android】使用setContentView(View)这样切换界面布局
p21.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">
<TextView android:id="@+id/textView1" android:text="p21"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/changeText"></Button>
</LinearLayout>
p22.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">
<TextView android:id="@+id/textView1" android:text="p22"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/changeText"></Button>
</LinearLayout>
这种方式将两个布局首先加载进来并缓存,这样切换时无需重复初始化代码简化如下:/**
*
*/
package com.itest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* @author Robin
*/
public class ITestP2Activity extends Activity {
Button b1;
Button b2;
View v1;
View v2;
/** Called when the activity is first created. */
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
//缓存View1
v1 = getLayoutInflater().inflate( R.layout.p21, null );
//缓存View2
v2 = getLayoutInflater().inflate( R.layout.p22, null );
//动态修改v1中内容
b1 = (Button) v1.findViewById( R.id.button1 );
b1.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v )
{
jumpToDevicelistB2();
}
} );
b2 = (Button) v2.findViewById( R.id.button1 );
b2.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v )
{
jumpToMainB1();
}
} );
//切换到v1
setContentView( v1 );
}
void jumpToDevicelistB2()
{
setContentView( v2 );
//无需重复初始化
}
void jumpToMainB1()
{
setContentView( v1 );
//无需重复初始化
}
}
转自:http://blog.csdn.net/lsj19830812/article/details/7107240
页:
[1]