2012-09-12 59 views
6

我有一個ListView,它在手機上效果很好。現在我正在製作平板電腦用戶界面,左邊是ListView,右邊是詳細信息。Android:ListView選擇後保持藍色背景

當我觸摸一個項目時,只要按下它就會閃爍藍色。我想保持藍色,直到選中另一個項目,就像Nexus 7上的Gmail應用程序一樣。

實現該目標的最簡潔方法是什麼?我寧願避免手動設置背景,我認爲有一種方法可以將元素標記爲「活動」元素,然後相應地設置主題。

+0

你可以看到這個鏈接可能會有所幫助:HTTP:/ /stackoverflow.com/questions/5682053/listview-item-wont-stay-selected –

+0

你可以設置列表視圖項目的點擊ListView項目的視圖的背景顏色。 –

回答

17

什麼是最簡單的方法來實現這一目標?

你在找什麼是被稱爲「激活」狀態。要做到這一點:

步驟#1:在res/values-v11/,有一個樣式資源,執行activated。例如,對於已定義那裏AppTheme聲明一個新的項目,去的東西,如:

<resources> 

    <style name="AppTheme" parent="android:Theme.Holo.Light"></style> 

    <style name="activated" parent="AppTheme"> 
     <item name="android:background">?android:attr/activatedBackgroundIndicator</item> 
    </style> 

</resources> 

第2步:定義同風格res/values/任何較舊的設備,就像一個存根風格的資源,所以引用它繼續工作:

<resources> 

    <style name="AppTheme" parent="android:Theme.Light"/> 

    <style name="activated" parent="AppTheme"/> 

</resources> 

第3步:在在ListView行佈局XML資源,增加style="@style/activated"根元素

聖屬性列表EP#4:設置ListView是單選項列表,如在ListFragment以下行:

getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

可以在this sample projectthis sample projectthis sample project看到這個動作。對於那些第一次兩個樣本更多的背景,請參閱本SO問題:Complete Working Sample of the Gmail Three-Fragment Animation Scenario?

+0

它工作得很好,它確實比以編程方式更改背景好得多。非常感謝你! – erwan

4

使用的

android.R.layout.simple_list_item_activated_1

代替

R.layout.simple_list_item_checkable_1

只爲有人檢查某一天。

2

經過幾天的搜索和拉我的頭髮我剛剛發現,activatedBackgroundIndicator也可在ActionBarSherlock造型系統。大多數開發向後兼容應用程序的開發人員使用ActionBarSherlock,因此在大多數情況下使用ActionBarSherlock是一個不錯的選擇。因此,而不是使用android:background="?android:attr/activatedBackgroundIndicator"將前11給android的版本錯誤,只需使用:android:background="?activatedBackgroundIndicator"

這裏是行的例子佈局XML代碼:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
    //note the activatedBackgroundIndicator 
android:background="?activatedBackgroundIndicator" 
android:minHeight="?android:attr/listPreferredItemHeight" 
android:paddingBottom="2dip" 
android:paddingTop="2dip" > 

<TextView 
    android:id="@+id/text1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical" 
    android:minHeight="?android:attr/listPreferredItemHeight" 
    android:paddingLeft="6dip" 
    android:paddingRight="6dip" 
    android:textSize="15sp" /> 

<TextView 
    android:id="@+id/text2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center_vertical" 
    android:minHeight="?android:attr/listPreferredItemHeight" 
    android:paddingRight="5dip" 
    android:textSize="20dip" /> 
    </LinearLayout> 
+0

'所以,而不是使用android:background =「?activatedBackgroundIndicator」,它會在11之前的Android版本中發生錯誤,只需使用:android:background =「?activatedBackgroundIndicator」'什麼?你能解釋一下嗎? – kuchi

+0

謝謝4點指出。糾正了答案。 –