2016-12-27 31 views
0

如下面的代碼所示,我有一些視圖,我想向視圖添加選擇器顏色,以便在單擊視圖時更改其顏色。就像在列表視圖中點擊一個項目時發生的那樣,這就是我正在嘗試做的事情 。如何以編程方式將選擇器顏色添加到視圖

我提到的一些帖子,我troed以下兩項:

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 
+0

那麼你想改變項目的背景一旦點擊? (和項目我指的是一個listItem) –

+0

是的,我想改變背景的顏色一旦clciked..and我的意見在發​​布的代碼,是正常的看法,你可以看到..它是一個列表視圖 – user2121

+0

它應該使用setBackgroundResource,你可以添加完整的例子嗎? – petrumo

回答

0

你需要得到一個指向android.R.attr.listChoiceBackgroundIndicator作爲繪製在link中建議並以編程方式進行設置。

// 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); 
+0

我試過你的答案,實際上我沒有工作,當點擊視圖時沒有任何效果,而且我可以從API 16獲得,而我的目標是API 15 – user2121

相關問題