简体   繁体   English

如何在具有较大项目列表的listView中突出显示所选项目?

[英]How to highlight selected item in listView with a large list of items?

I have a custom ListView in a tablet app where there's a ListView on the left and detailed fragment on the right, when you select an Item on the left from the listView I want it to be highlighted and stay highlighted (I did this part) but when I scroll down to the bottom of the list and back and due to The recycling of views it forgets the highlighting, how can I do it in a different way? 我在平板电脑应用程序中有一个自定义的ListView,左侧有一个ListView,右侧有详细的片段,当您从listView的左侧选择一个项目时,我希望它突出显示并保持突出显示(我做了这部分),但是当我向下滚动到列表的底部并返回时,由于视图的回收而忘记了突出显示,我该如何以其他方式进行处理?

Here's the code I used in the adapter for the ListView: 这是我在ListView适配器中使用的代码:

protected LinearLayout selectedItem;
protected LinearLayout selectedItemPosition = -1;
.
.
.
@Override
public int getViewTypeCount() {
    return 3; // I have 3 types of list Items, this part is working fine..
}
public int getItemViewType(int pos) {
    // This part works fine too
}
.
.
public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder;
.
.
.
if (selectedItemPosition == pos) {
    holder.listItem.setSelected(true);
}

final LinearLayout listItem = holder.listItem;      

holder.listItem.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (clickCallback != null) {                    
            if (activateOnClick) {
                if (selectedItemPosition > -1) {
                    selectedItem.setSelected(false);
                }
                selectedItemPosition = pos;
                listItem.setSelected(true);
                selectedItem = listItem;
            }
            clickCallback.callback(NewsItems.get(pos));
        }
    }
});

You can try to create custom selector for listview item - listview_selector.xml 您可以尝试为列表视图项创建自定义选择器-listview_selector.xml

<?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/yourColor" />
    <item android:state_enabled="true"
     android:state_focused="true" android:drawable="@color/yourColor" />
    <item android:state_enabled="true"
     android:state_selected="true" android:drawable="@color/yourColor" />
    <item
     android:drawable="@color/yourColor" />
</selector>

And then, use 然后,使用

listView.setSelector(R.drawable.listview_selector);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM