如何以编程方式将选择器颜色添加到视图中

时间:2016-12-27 13:02:17

标签: android listview view android-linearlayout

如下面的代码中所示,我有一些视图,我想为视图添加一个选择器颜色,以便在单击视图时其颜色会发生变化。正如在点击列表视图中点击某个项目时所发生的那样,这就是我的意思 试图做。

我提到了一些帖子,我考虑了以下两点:

view.setBackgroundResource(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color
view.setBackground(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color

但它不起作用,AndroidStudio用红色突出显示它们。

请让我知道如何以编程方式添加选择器颜色

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

    RelativeLayout relLay = (RelativeLayout) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_mainContainer);
    final TextView texVieShowMore = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showMore);
    final TextView texVieShowLess = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showLess);
    final TextView texVieShowMoreArrow = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showMoreArrow);
    final TextView texVieShowLessArrow = (TextView) view.findViewById(R.id.versicherungslisteactivity2_meinedocs_lisvie_footer_texVie_showLessArrow);

    view.setBackgroundResource(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color
    //view.setBackground(android.R.attr.listChoiceBackgroundIndicator);//highlighted with red color

1 个答案:

答案 0 :(得分:0)

您需要按照此link中的建议获取指向android.R.attr.listChoiceBackgroundIndicator的drawable,并以编程方式设置它。

// Create an array of the listChoiceBackgroundIndicator attribute
int[] attrs = new int[] { listChoiceBackgroundIndicator /* index 0 */};

// Obtain the styled attributes. 'themedContext' is a context with a
// theme, typically the current Activity (i.e. 'this')
TypedArray ta = themedContext.obtainStyledAttributes(attrs);

// To get the value of the 'listChoiceBackgroundIndicator' attribute that was
// set in the theme used in 'themedContext'. The parameter is the index
// of the attribute in the 'attrs' array. The returned Drawable
// is what you are after
Drawable drawableFromTheme = ta.getDrawable(0 /* index */);

// Then, free the resources used by TypedArray
ta.recycle();

// Finally, set drawable as background
view.setBackground(drawableFromTheme);