2011-09-19 88 views
2

想打一個Android應用程序與佈局開始,當你按下一個按鈕(稱爲stateButton)即在此佈局的佈局變爲MAIN2佈局包含另一個按鈕(稱爲boton2 ),當你推這一個時,你會回到第一個主體。從一個佈局視圖更改爲另一個並返回?

我想在不創建或啓動另一個活動的同一活動中執行此操作。

在這裏,我向您展示的部分代碼:

public class NuevoshActivity extends Activity 
implements SensorEventListener, OnClickListener { 
    private Button stateButton; 
    private Button boton2; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.main); 
     this.stateButton = (Button) this.findViewById(R.id.boton); 
     this.boton2 = (Button) this.findViewById(R.id.boton2);  
     stateButton.setOnClickListener(this); 
     boton2.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     if(v==stateButton) { 
      setContentView(R.layout.main2);    
     } 
     else if(v==boton2) { 
      setContentView(R.layout.main); 
     } 
    } 
} 

的電源只有一些圖像,文本視圖和按鈕。

但我有一些麻煩。難道它不是那麼簡單,或者我錯過了什麼或錯在哪裏?

回答

0

您的boton2按鈕將爲NULL,因爲按鈕的定義在main2.xml中。 您將能夠找到的唯一視圖是在main.xml中定義的視圖。

2

FrameLayout處理這個奇妙......通過對各個佈局​​和setVisibility(View.INVISIBLE);使用此與<include... contstruct加載多個其他佈局,那麼你就可以來回切換之間。

例如:

主要XML包括其他兩個佈局:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout android:id="@+id/frameLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> 
    <include android:id="@+id/buildinvoice_step1_layout" layout="@layout/buildinvoice_step1" android:layout_width="fill_parent" android:layout_height="fill_parent"></include> 
    <include android:id="@+id/buildinvoice_step2_layout" android:layout_width="fill_parent" layout="@layout/buildinvoice_step2" android:layout_height="fill_parent"></include> 
</FrameLayout> 

代碼以佈局之間進行切換:

findViewById(R.id.buildinvoice_step1_layout).setVisibility(View.VISIBLE); 
findViewById(R.id.buildinvoice_step2_layout).setVisibility(View.INVISIBLE); 

您還需要設置各個佈局的知名度當活動開始時(或XML),否則你會看到他們兩個 - 一個在另一個之上。

3

當您使用findViewById時,您實際上是試圖在由setContentView指定的佈局內查找視圖。因此,當您嘗試檢查按鈕時,一次又一次使用setContentView可能會帶來問題。

不是使用setContentView,而是將屏幕的2個佈局作爲子視圖添加到一次只顯示一個子視圖的視圖腳本。你可以指定顯示哪個孩子的索引。使用視圖腳本的好處是,如果在視圖之間切換時需要動畫,則可以輕鬆地爲視圖指定「in」和「out」動畫。這是一個更清潔的方法,然後再次調用setContentView。

0

謝謝!所有的信息都非常有用,可以理解很多事情,因爲C0deAttack評論說我在main2上的按鈕有麻煩。我所做的就是將View.VISIBLE和View.GONE設置爲每個佈局中我想要的TextView和Buttons。非常感謝你。

相關問題