[Andriod] 透過setContentView轉換layout

  • 14450
  • 0

透過setContentView, 雖然可在layout之間轉換, 但仍然是使用同個Activity

透過setContentView, 雖然可在layout之間轉換, 但仍然是使用同個Activity

res\layout\layout1.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/layout1" />
    <Button
        android:id="@+id/btGo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="@string/go" />
</TableLayout>

 

res\layout\layout2.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/layout2" />
    <Button
        android:id="@+id/btBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="@string/back" />
</TableLayout>

 

src\...\Activity1.java

package com.example.excercise3;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;

public class Activity1 extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout1);
	}

	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btGo:
			setContentView(R.layout.layout2);
			break;
		case R.id.btBack:
			setContentView(R.layout.layout1);
			break;	
		}
	}

}