更改ListView上所选项目的背景颜色

KaH*_*HeL 52 android android-layout

我想知道如何更改listView上所选项目的背景颜色.我只想更改用户点击的特定项目,这意味着如果用户点击另一个项目,它将是突出显示的项目.好吧,因为我希望它尽可能保持简单并使用默认的android listview我使用此代码:

record_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                try{
                    for (int ctr=0;ctr<=record_items.length;ctr++){
                        if(i==ctr){
                            record_list.getChildAt(ctr).setBackgroundColor(Color.CYAN);
                        }else{
                            record_list.getChildAt(ctr).setBackgroundColor(Color.WHITE);
                        }
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                Log.v("Selected item",record_list.getItemAtPosition(i));
            }
        });
Run Code Online (Sandbox Code Playgroud)

好的,这个工作正常,但问题是它很慢.现在我想知道是否有任何其他方法可以做到,它将提供与我相同的输出.

我尝试使用record_list.getSelectedView().setBackgroundColor(Color.CYAN);但它给了我一个空指针异常.

我也尝试了selector.xml,但它也没有做到这一点.此外,ListView上有一个名为listSelector的属性.如文档"Drawable用于指示列表中当前选定的项目"所述,它是可绘制的.我也相信这应该可以做到这一点,是的,它可以在我的模拟器上完成,但不是在我的Galaxy选项卡上.我也尝试了其他方法,但没有任何方法可行,因为我想要它.

Est*_*eam 73

您可以跟踪当前所选元素的位置:

    OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
                mSelectedItem = position;
                mAdapter.notifyDataSetChanged();
        }
    };
Run Code Online (Sandbox Code Playgroud)

并覆盖适配器的getView方法:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final View view = View.inflate(context, R.layout.item_list, null);

        if (position == mSelectedItem) {
            // set your color
        }

        return view;
    }
Run Code Online (Sandbox Code Playgroud)

对我来说,这就是诀窍.

  • Esteam的解决方案是正确的.仅使用view.setSelected(true)的问题是这些视图被回收.只要您有足够大的列表进行滚动,这将不再有效. (11认同)
  • 您应该只需在onItemClick侦听器中设置view.setSelected(true):http://stackoverflow.com/questions/16189651/android-listview-selected-item-stay-highlighted (2认同)
  • 这将在Lollypop中分解 - 如果您在项目上设置背景,则不再看到那些精美的点击动画. (2认同)

Rag*_*dan 69

您可以使用选择器.更改颜色值并根据需要修改以下内容.

可绘制文件夹中的bkg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" 
    android:drawable="@drawable/pressed" />
<item  android:state_focused="false" 
    android:drawable="@drawable/normal" />
</selector>
Run Code Online (Sandbox Code Playgroud)

drawable文件夹中的pressed.xml

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FF1A47"/>  // color   
<stroke android:width="3dp"
        android:color="#0FECFF"/> // border
<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp" // for rounded corners
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>
Run Code Online (Sandbox Code Playgroud)

drawable文件夹中的normal.xml

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
<solid android:color="#FFFFFF"/>    
<stroke android:width="3dp"
        android:color="#0FECFF" />

<padding android:left="5dp"
         android:top="5dp"
         android:right="5dp"
         android:bottom="5dp"/> 
<corners android:bottomRightRadius="7dp"
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp"
         android:topRightRadius="7dp"/> 
</shape>
Run Code Online (Sandbox Code Playgroud)

将可绘制的背景设置为listview自定义布局,以便为每行充气

我建议使用自定义列表视图和自定义适配器.

  android:background="@drawable/bkg"     
Run Code Online (Sandbox Code Playgroud)

如果您尚未使用自定义适配器,则可以将listselector设置为listview,如下所示

   android:listSelector="@drawable/bkg" 
Run Code Online (Sandbox Code Playgroud)

  • 目前,当我点击一个列表项时,它的颜色发生了变化,然后在发布后将其颜色更改为默认颜色.但我的要求是我要将点击的项目显示为选中,直到我不点击其他列表项 (6认同)

Hir*_*tel 23

定义变量

private ListView mListView;
Run Code Online (Sandbox Code Playgroud)

初始化变量

mListView = (ListView)findViewById(R.id.list_view);
Run Code Online (Sandbox Code Playgroud)

listview的OnItemClickListener

   mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adpterView, View view, int position,
                long id) {
            for (int i = 0; i < mListView.getChildCount(); i++) {
                if(position == i ){
                    mListView.getChildAt(i).setBackgroundColor(Color.BLUE);     
                }else{
                    mListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
                }
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

构建并运行项目 - 完成

  • 要小心,如果列表长度超过一个屏幕高度,它将使用空指针进行压缩.此外,如果您有一个包含数千个项目的列表,当您只看到一些项目时,它将一个接一个地进行. (2认同)

ssa*_*nko 15

如果您希望在单击项目后保持项目突出显示,则需要手动将其设置为在onItemClick监听器中选中

Android ListView所选项目保持突出显示:

myList.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {   
        view.setSelected(true); // <== Will cause the highlight to remain
        //... do more stuff                          
    }});
Run Code Online (Sandbox Code Playgroud)

这假设您的选择器中有一个state_selected项:

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  <item android:state_enabled="true" android:state_pressed="true" android:drawable="@color/red" />
  <item android:state_enabled="true" android:state_focused="true" android:drawable="@color/red" />
  <item android:state_enabled="true" android:state_selected="true" android:drawable="@color/red" />
  <item android:drawable="@color/white" />
</selector>
Run Code Online (Sandbox Code Playgroud)


JMa*_*Max 7

方法1:

更新xml布局活动/片段中的ListView:

<ListView
   ...
   android:choiceMode="singleChoice"
   android:listSelector="@android:color/darker_gray"
/>
Run Code Online (Sandbox Code Playgroud)

就是这样,你完成了!

如果你想要一种编程方式来处理这个,那么使用方法2 ......

方法2:

如果您正在使用ListFragment,则可以使用视图来覆盖onListItemClick()以设置颜色.保存当前选定的视图以重置上一个选择的颜色.

请注意,这仅适用于适合一个屏幕的列表视图,因为视图可以回收.

public class MyListFragment extends ListFragment {
    View previousSelectedItem;
...
    @Override
    public void onListItemClick(ListView parent, View v, int position, long id) {
        super.onListItemClick(parent, v, position, id);
        if (previousSelectedItem!=null) {
            previousSelectedItem.setBackgroundColor(Color.WHITE);
        }
        previousSelectedItem=v;
        v.setBackgroundColor(Color.BLUE);
    }
}
Run Code Online (Sandbox Code Playgroud)


Nir*_*ali 6

首先,您可以在drawable文件夹中创建如下所示的选择器xml文件 drawable/list_item_selector.xml

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

    <item android:state_activated="true">
      <shape android:shape="rectangle">
        <solid android:color="#333333" />
        <padding android:left="5dp" android:right="5dp" />
      </shape></item>
    <item><shape android:shape="rectangle">
            <solid android:color="#222222" />
        </shape></item>

</selector>
Run Code Online (Sandbox Code Playgroud)

然后在listview中将背景指定为

android:background="@drawable/list_item_selector"
Run Code Online (Sandbox Code Playgroud)


Emi*_*mil 6

对于那些想知道在向上滚动时要保持选择行的确切需要做什么的人.这是state_activated其余由内部功能处理,您不必担心切换,并可以选择多个项目.我不需要使用notifyDataSetChanged()或setSelected(true)方法.

将此行添加到您的选择器文件中,对于我drawable\row_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@android:color/holo_blue_light"/>

    <item android:state_enabled="true" android:state_pressed="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@android:color/holo_blue_bright" />
    <item android:state_enabled="true" android:state_selected="true" android:drawable="@android:color/holo_blue_light" />
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_light" />

    <item android:drawable="@android:color/transparent"/>
</selector>
Run Code Online (Sandbox Code Playgroud)

然后在layout\custom_row.xml中

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:background="@drawable/row_background"
        android:orientation="vertical">
  <TextView
        android:id="@+id/line1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,我正在使用ListView适配器,使用myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); 和myList.setMultiChoiceModeListener(new MultiChoiceModeListener()...

从这个例子:http://www.androidbegin.com/tutorial/android-delete-multiple-selected-items-listview-tutorial/

此外,您(应该)将此结构用于列表 - 适配器耦合:List myList = new ArrayList();

而不是:ArrayList myList = new ArrayList();

说明:在Java中键入List vs type ArrayList


Tao*_*hok 5

我发现的最简单的方法:

在您的活动 XML 中添加以下几行:

<ListView 
... 
android:choiceMode="singleChoice"
android:listSelector="#666666"
/>
Run Code Online (Sandbox Code Playgroud)

或以编程方式设置这些属性:

listView.setSelector(Drawable selector)
listView.setSelector(int resourceId)
Run Code Online (Sandbox Code Playgroud)

我的具体例子:

   <ListView
            android:choiceMode="singleChoice"
            android:listSelector="#666666"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listView"/>
Run Code Online (Sandbox Code Playgroud)

感谢 AJG:https ://stackoverflow.com/a/25131125/1687010