2016-12-29 3 views
0

У меня есть linearlayout и как показано ниже в коде1, я добавляю к нему фон для изменения его внешнего вида/фона при его выборе.Как добавить селектор к виду программно

в Кодекса2 ниже, я надуть вид и я хочу, чтобы добавить один и тот же селектор/фон «андроид: фон =„Android: атр/listChoiceBackgroundIndicator“» к представлению завышены в Кодекса2

как я могу делать это программно?

code1:

<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"> 

code2:

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' макет в xml? если не использовать 'relLay.setClickable (true)'. PS. default 'listChoiceBackgroundIndicator' поддерживает только отключенное/нажатое/сфокусированное состояние (оно не поддерживает выбранное состояние) https://github.com/android/platform_frameworks_base/blob/master/core/res/res/drawable/list_selector_background.xml –

Смежные вопросы