Question

Hello i have one imageView on my view. In my activity i create in onCreate an ArrayList, where if you click on the imageView, a name will be added. So if the list contains this name, the filled star image will be loaded from the drawable folder. And here is my problem: How do i write that you click on the imageView and the other image will be load? So if theres the filled star the empty star should be loaded.

    final ImageView img = (ImageView) rootView.findViewById(R.id.imageView1);

    if (starredList.contains(txt1[p])){
        img.setImageResource(R.drawable.ic_action_important);       
    }
    else{
        img.setImageResource(R.drawable.ic_action_not_important);
    }



    img.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View view)
        {

        Object tag = img.getTag();

            int id = tag == null ? -1 :(Integer) tag;


            if (id==R.drawable.ic_action_important){
                img.setImageResource(R.drawable.ic_action_not_important);

            }
            if (id==R.drawable.ic_action_not_important){
                    img.setImageResource(R.drawable.ic_action_important);
                 starredList.add(txt1[p]);
                 Toast.makeText(getActivity(), txt1[p]+" wurde ihren Favoriten hinzugefügt", Toast.LENGTH_LONG).show();

                } 




        }
    });

Thank you in advance!

Was it helpful?

Solution

Use ToggleButton and handle those drawable through selector.

create an XML drawable using selector named favorite_button_image.xml in drawable folder and add your drawables as item in the following XML as below...

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_action_important"
        android:state_checked="true"/>
    <item android:drawable="@drawable/ic_action_not_important"
        android:state_checked="false"/>
</selector>

set this favorite_button_image as a drawable in the ToggleButton as below...and add this ToggleButton to your Layout XML instead of ImageView. You will get what you wanted to do.

<ToggleButton
    android:id="@+id/star"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/favorite_button_image"
    android:textOff=""
    android:textOn="" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top