2014-04-21 24 views
1

我有我實現了作爲組成的複合控件的自定義按鈕:在根改變一個Android複合控件的啓用狀態,同時保持其樣式設置

  • 一個FrameLayout裏,這是我使用@android:style/Widget.Holo.Button進行了樣式設計,以便像按鈕一樣進行查看和操作;
  • 兩個TextView作爲上述FrameLayout的子項,配置了duplicateParentState = true,這樣如果我將FrameLayout設置爲false,它們將顯示爲禁用。

修整後的XML看起來如下:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    style="@android:style/Widget.Holo.Button" 
    android:id="@+id/layout_button"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="PLACEHOLDER" 
    android:layout_gravity="center_horizontal|top" 
    android:duplicateParentState="true" 
    android:id="@+id/text_button1" 
    android:textSize="24sp"/> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="PLACEHOLDER" 
    android:layout_gravity="center_horizontal|bottom" 
    android:duplicateParentState="true" 
    android:id="@+id/text_button2" 
    android:textSize="12sp"/> 
</FrameLayout> 

隨着對複合控件的XML佈局,我創建了一個Java實現的Android文檔,它看起來是這樣的描述:

public class CustomButton extends FrameLayout { 
    public CustomButton (Context context, AttributeSet attrs) { 
    super(context, attrs); 

    LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    layoutInflater.inflate(R.layout.control_custombutton, this, true); 
    } 
} 

如果我正確理解,當這種控制被用來構建的層次結構將(指示括號其中該視圖中定義):

FrameLayout (Java) -> FrameLayout (XML) -> 2x TextViews (XML) 

我希望能夠切換我的自定義按鈕是否處於啓用或不獲取到按鈕的引用,並設置enabled屬性,像這樣:

CustomButton button = (CustomButton)findViewById(R.id.button); 
button.setEnabled(false); 

然而,這並不工作,因爲在XML中定義的FrameLayout不會繼承其父級的屬性,因此該按鈕將繼續顯示爲已啓用。

我已經嘗試在XML中定義的FrameLayout中添加duplicateParentState = true,但在這種情況下,我的樣式屬性被覆蓋/繼承,並且控件看起來不再像按鈕一樣。

我也嘗試過使用合併標籤並以編程方式設置樣式,但據我所知,不能通過編程方式設置視圖樣式。

我的解決方法到目前爲止已經覆蓋上的CustomButton的的setEnabled()方法,像這樣:

public void setEnabled(boolean enabled) { 
    super.setEnabled(enabled); 
    findViewById(R.id.button_rootLayout).setEnabled(enabled); 
} 

這工作,但現在我必須爲我想以編程方式修改每個屬性做到這一點,我有與註冊OnClickListeners類似的問題。

有沒有更好的方法?

+0

是否有任何理由你從FrameLayout而不是按鈕派生自定義按鈕? –

+0

Button不是ViewGroup,所以我不能將誇張的Layout附加到它上面,而且我需要Layout,因爲定位太複雜,無法用Button的標準setText()處理。 – Zecrates

+0

當你說你的FrameLayout是用XML定義的時候,我很困惑。你應該可以在XML中使用''標籤。你能顯示佈局文件的相關部分嗎? –

回答

0

如何:

public void setEnabled(boolean enabled) { 
    super.setEnabled(enabled); 
    setClickable(enabled); 
} 

這是我落得這樣做。

相關問題