2016-12-27 13 views
0

以下のコードに示すように、いくつかのビューがあり、セレクタの色をビューに追加して、ビューをクリックすると色が変わるようにします。リストビュー内のアイテムをクリックするとまったく同じように、私は をしようとしています。ビューにセレクタの色をプログラムで追加する方法

私はいくつかの記事を参照して、私は次の両方をtroed:

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

が、それは仕事をdoesntのとAndroidStudioは赤い色でそれらを強調表示します。あなたがようandroid.R.attr.listChoiceBackgroundIndicatorを指す描画可能を取得する必要があり

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 ..と投稿されたコードの私のビューは、通常のビューです背景の色を変更するwant.itはリストビュー – user2121

+0

ですsetBackgroundResourceで動作するはずですが、完全な例を追加できますか? – petrumo

答えて

0

プログラムで

コード私ののVIEへのセレクタの色を追加する方法を教えてくださいこの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

関連する問題