简体   繁体   中英

Android - States for different imageview resources as a listview items

I've customized a listview item. Each item list has an imageview.

The type of the imageview is defined by a category variable, that I save in a DB.

So lets's say there are three items in the listview with those three categories - blue, red and black.

So the bindView of the CursorAdapter is as following -

    public void bindView(View view, Context context, Cursor cursor) {

String cat = cursor.getString(cursor.getColumnIndex(Constans.CATEGORY));

ImageView iv = (ImageView) view.findViewById(R.id.imageView);

    if (cat.equalsIgnoreCase("black")) {
                iv.setImageResource(R.drawable.black_un);
            }

            if (cat.equalsIgnoreCase("blue")) {
                iv.setImageResource(R.drawable.blue_un);
            }

            if (cat.equalsIgnoreCase("red")) {
                iv.setImageResource(R.drawable.red_un);
            }

}

Now what I would like to do is when the listviewitem is being pressed - I want that the imageview will show the relevant "pressed" image -

what I mean is that now the imageview is showing the non pressed state image - but when the user pressing on the listview item I want that it will show the "pressed" image - and than the imageview will present the non pressed image again - just as you can do with a button.

Any ideas how can I do that? Mind that there's a different image at each listview raw - depends of course on the category.

use selector for this:

selector.xml:

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

<item android:drawable="@drawable/not_pressed_image" android:state_pressed="false"></item>
<item android:drawable="@drawable/pressed_image" android:state_pressed="true"></item>

</selector>

Rather than setting one drawable set the selector like:

iv.setImageResource(R.drawable.selector);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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