2012-10-05 48 views
11

在我的應用程序中,我想在平板電腦上執行類似gmail應用程序的操作,在左側列出項目並在右側有一個片段該項目的內容,就像gmail應用程序一樣,該內容在選擇後正在下載。當我點擊一個項目後,我希望它保持高亮顯示,直到我改變了選擇。 我達到了這一點,但只有當我點擊兩次相同的項目,所以首先我點擊,選擇作品,然後項目回到其默認狀態,如果我再次點擊它,選擇器(用於選中狀態)是可見的。Android:將列表視圖項目設置爲「已選中」(突出顯示)

這是我迄今爲止:

1)。選擇器(listitem_background.xml)

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@drawable/solid_white" android:state_pressed="false" android:state_selected="false"/> 
    <item android:drawable="@drawable/listitem_pressed" android:state_pressed="true"/> 
    <item android:drawable="@drawable/listitem_focused" android:state_selected="true"/> 

</selector> 

2)對於該列表項的頂部線性佈局:

android:background="@drawable/listitem_background" 

(我也嘗試將它設置爲listselector)

3)這是ListView:

<ListView 
    android:id="@+id/my_list_view" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:choiceMode="singleChoice" 
    android:dividerHeight="1dp" 
    android:drawSelectorOnTop="true" 
    android:fadeScrollbars="true" 
    android:fastScrollEnabled="true" 
    android:focusable="true" 
    android:focusableInTouchMode="true" 
    android:scrollbarFadeDuration="100" 
    android:scrollbars="vertical" /> 

4)在部分代碼我試圖玩這個:

@Override 
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
    view.setSelected(true); 
    ... 
} 

[編輯]其實我已經注意到,在選擇之後,該片段在右提交丟失屏幕一側。如果我不提交它就像一個魅力的片段...... 我想我需要像這樣的選擇:

<item android:drawable="@drawable/listitem_focused" android:state_activated="true" android:state_focused="false"/> 

但顯然不是這個......

回答

45

OK,終於拿到了我的答案。

的想法是使用在選擇的state_activated和

listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE) 
代碼

,或者

android:choiceMode="singleChoice" 
在XML

,當然

這是選擇應該如何看起來像:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 

    <item android:drawable="@drawable/solid_white" android:state_activated="false"/> 
    <item android:drawable="@drawable/solid_white" android:state_activated="false" android:state_pressed="false"/> 
    <item android:drawable="@drawable/listitem_pressed" android:state_pressed="true"/> 
    <item android:drawable="@drawable/listitem_focused" android:state_activated="true"/> 

</selector> 

這是列表項的佈局應該如何:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/listitem_background" 
    android:orientation="vertical" > 
... 
<LinearLayout/> 
+0

感謝。這對我有效:) –

+0

不適用於api 8 –

4

我面臨着同樣的問題,然後我只需要在我的項目視圖XML簡單的線條。

android:background="?android:attr/activatedBackgroundIndicator"

This post可以幫助

+0

僅適用於api級別> = 14 – johntheripp3r

相關問題