2016-12-29 119 views
0

我有一個線性佈局,如下面的代碼1所示,我添加了一個背景以在選定時更改其外觀/背景。如何以編程方式將選擇器添加到視圖

在下面CODE2,我膨脹的圖,我想添加相同的選擇/背景「機器人:背景=‘機器人:ATTR/listChoiceBackgroundIndicator’」 在CODE2充氣視圖

我怎樣才能以編程方式進行?

代碼1

<LinearLayout 
      android:id="@+id/versicherungs_verDetailsListFooter_container" 
      android:layout_width="match_parent" 
      android:layout_height="@dimen/vers_height" 
      android:layout_below="@id/horizontalDivider0" 
      android:clickable="true" 
      android:orientation="horizontal" 
      android:paddingLeft="15dp" 
      android:visibility="gone" 
      android:weightSum="1" 
      android:background="?android:attr/listChoiceBackgroundIndicator"> 

碼2

final LinearLayout linLay = (LinearLayout) findViewById(R.id.versicherungs_verDetailsListFooter_container); 

    LayoutInflater inflator = this.getLayoutInflater(); 
    final View view = inflator.inflate(R.layout.versicherungs_docs_footer, null); 

    RelativeLayout relLay = (RelativeLayout) view.findViewById(R.id.versicherungs_footer_mainContainer); 
    final TextView texVieShowMore = (TextView) view.findViewById(R.id.showMore); 
    final TextView texVieShowLess = (TextView) view.findViewById(R.id.showLess); 
    final TextView texVieShowMoreArrow = (TextView) view.findViewById(R.id.showMoreArrow); 
    final TextView texVieShowLessArrow = (TextView) view.findViewById(R.id.showLessArrow); 

    //how to add the selector "?android:attr/listChoiceBackgroundIndicator" to the RelativeLayout "relLay" 
+1

我想'主題#resolveAttribute'會做得到'resourceId' – pskink

+0

@pskink將ü請提供一個例子 – user2121

+0

的把戲我沒有任何 – pskink

回答

1

您需要解決從主題屬性:

TypedValue typedValue = new TypedValue(); 
if (getTheme() != null) { 
    getTheme().resolveAttribute(R.attr.listChoiceBackgroundIndicator, typedValue, true); 
} 
int drawableResourceId = typedValue.resourceId; // it can by equal 0 

,然後設置視圖的背景資源:

relLay.setBackgroundResource(drawableResourceId); 
+0

我試過你的建議答案..但不幸的是,當我點擊視圖它不會改變,因爲如果沒有屬性分配爲選擇器/背景 – user2121

+0

標誌'clickable'設置爲true爲' relLay' layout in xml?如果不使用'relLay.setClickable(true)'。 PS。默認'listChoiceBackgroundIndicator'只支持禁用/按下/關注狀態(不支持選中狀態)https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable/list_selector_background.xml –

相關問題