2011-03-30 54 views
3

我知道如何啓用/發現它後禁用佈局XML定義的按鈕:有條件地顯示按鈕

testBtn = (Button)findViewById(R.id.test); 
比有條件裝載佈局

但是其他的,有沒有辦法在我的代碼「使用告訴佈局XML,但不加載在那裏定義的按鈕「?

回答

11

要在Xml中設置視圖的可見性,請使用android:visibility屬性。

以下設置按鈕可見性消失。當設置爲消失時,Android不會顯示該按鈕,並且在佈局計算過程中不包括它的大小。

<Button android:id="@+id/mybutton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Hello" 
      android:visibility="gone"/> 

設置android:visibility =「不可見」不會顯示按鈕,但會在佈局計算中包含它。

<Button android:id="@+id/mybutton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Hello" 
      android:visibility="invisible"/> 

要以編程方式顯示代碼中的按鈕,請調用setVisibility()方法。

Button btn = (Button)findViewById(R.id.thebuttonid); 
btn.setVisibility(View.VISIBLE); //View.GONE, View.INVISIBLE are available too. 
+0

您的假設是正確的 - 我不希望它呈現爲佈局的一部分。我想在代碼中動態地控制它,API方法是做什麼的? – an00b 2011-03-30 16:46:47

+1

非常感謝。您剛剛在Android世界中拯救了幼兒的生命。 :) – an00b 2011-03-30 16:56:57

+0

不客氣。快樂編碼=) – 2011-03-30 16:59:41