2013-06-28 57 views
0

我正在開發自定義控件,並希望使用相同顏色的ListView控件用於突出顯示所選項目。如何獲得ListView選擇顏色值?

我試圖使用context.getResources().getDrawable(android.R.drawable.list_selector_background) 然後在我的視圖上使用setBackgroundDrawable(),但背景仍然是透明的。

我不想使用狀態,我只需要一個顏色值或可繪製我可以在我的控件上用作背景。

請幫忙!

回答

0

那麼列表選擇器drawable在默認狀態下(通常)是透明的。所以你必須先改變狀態。

按下狀態可用於例如:

Drawable drawable = context.getResources().getDrawable(android.R.drawable.list_selector_background); 
drawable.setState(new int[] {android.R.attr.state_pressed}); 
x.setBackgroundDrawable(drawable); 

哪裏x您的看法。

+0

感謝您的建議。我試過使用android.R.attr.state_pressed,android.R.attr.state_focused和兩者結合。但是背景仍然是透明的:( – Lev

2

我認爲最好的辦法是在你的XML您的ListView使用一個這樣的選擇:

<ListView 
    .... 
    android:listSelector="@drawable/selectable_background" 
    ..../> 

然後在你繪製的文件夾添加一個XML文件是這樣的:

<selector xmlns:android="http://schemas.android.com/apk/res/android" 
    android:exitFadeDuration="@android:integer/config_mediumAnimTime" > 

    <item android:state_pressed="false" android:state_focused="true" 
      android:drawable="@drawable/list_focused" /> 

    <item android:state_pressed="true" 
      android:drawable="@drawable/pressed_background" /> 

    <item android:drawable="@android:color/transparent" /> 
</selector> 

並再次在您的可繪製文件夾中添加此其他xml文件:

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 

    <solid android:color="@color/green" /> 

</shape> 

並在您添加的drawable-hdpi這9補丁文件(改變顏色或文件,或使用本網站創建自己的一個http://android-holo-colors.com/):

https://dl.dropboxusercontent.com/u/33565803/StackOverFlowExamples/list_focused.9.png

這樣你應該能夠對你的列表視圖的自定義高亮顏色。

編輯:

可點擊視圖的背景:

android:background="@drawable/pressed_button" 

選擇默認的ListView高亮顯示顏色(可繪製文件夾內pressed_button.xml):

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@android:drawable/list_selector_background" 
     android:state_pressed="true" /> 
    <item android:drawable="@android:color/transparent" 
     android:state_focused="true" /> 
    <item android:drawable="@android:color/transparent" /> 
</selector> 
+0

但我不想自己的顏色,我想重複使用與ListView完全相同的顏色標準,而且我的控件不是基於ListView的,它是一個自定義控件 – Lev

+0

其實我強烈推薦您可以http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html自定義您的應用到您自己的環境顏色。 – jpardogo

+0

不同版本和手機的默認顏色更改...如此是什麼你想要的?只是默認的一個,不管它是什麼...爲什麼你不定製你的應用程序?它是建議,你可以提供一個很好的自己的環境演示 – jpardogo

0

你可以嘗試像這,

例如,你需要得到使用以下代碼列出項目視圖
int visiblePosition = listview.getFirstVisiblePosition();
View view = listview.getChildAt(1 - visiblePosition);

//要獲取特定列表視圖項的顏色並設置它,
查看newView = listview.getChildAt(5-visiblePosition);
newView.setBackgroundColor(((ColorDrawable)view.getBackground())。getColor());