Search code examples
javaandroidlistviewcustom-adapter

Set the color of particular element on item in custom adapter


For example I have Custom Adapter List View, and my list item is a layout that contains different elements: textview, imageView and so on. How can I set the color of imageview of selected list item? Suppose I want to add this item in favourite and I want to change the color of star favourite for yellow color. Thank you)

       list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                                           int position, long id) {

                Toast.makeText(getActivity(), PlaceName[position] + " in favourite", 
Toast.LENGTH_SHORT).show();
//Do smth here, set the color of element on item, add to favourite and something else
                return true;
            }
        });

Solution

  • Well, you have this line:

    public boolean onItemLongClick(AdapterView<?> parent, View view,
                                               int position, long id) {
    

    https://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html

    According to the docs, view is the layout that you actually clicked, so you can get the child of that View using something like this:

    ImageView favorite = view.findViewById(R.id.yourFavoriteImageView);
    

    Note that if you scroll through your list, the layout might render again, and your change won't be visible again.