How to highlight ListView-Items

大兔子大兔子 提交于 2019-12-03 05:44:43
st0le

You should use a Selector.

This question and its answer might help....

@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
        {
            for(int a = 0; a < parent.getChildCount(); a++)
            {
                parent.getChildAt(a).setBackgroundColor(Color.BLACK);
            }

            view.setBackgroundColor(Color.RED);

        }

In your Activity:

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long itemid) {
            itemOnclickList(position, view);
        }
    });

    public void itemOnclickList(int position, View view) {      
    if (listview.isItemChecked(position)) {                           
       view.setBackgroundDrawable(getResources().getDrawable(R.drawable.image_checked));            
    } else {    
    view.setBackgroundDrawable(getResources().getDrawable(R.drawable.image_uncheck));           
    }
    adapter.notifyDataSetChanged();

}

In your Adapter:

  public View getView(int position, View view, ViewGroup parent) {
    View convertView = inflater.inflate(R.layout.listdocument_item, null);      

        ListView lvDocument = (ListView) parent;
        if (lvDocument.isItemChecked(position)) {
            convertView.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.image_checked));               
        } else {
            convertView.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.image_uncheck));               
        }

    return convertView;
}

Good luck!

Mercury

This is how it should look using selector:

Create a file within drawable called selector_listview_item.xml, which looks like (change the colors to your own):

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

Now in your layout which describes the list row (e.g. layout_list_row.xml), On the root layout add the android:background="@drawable/selector_listview_item", So the layout would look something like:

<?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="50dp"
    android:background="@drawable/selector_listview_item" <!-- this is the important line -->
    android:orientation="vertical">

    <!-- more stuff here -->
</LinearLayout>

(Note: you might want to add android:focusable="false" on you items within that listview row, to make the row clickable, as mentioned here)

Done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!