Sabatino Sabatino - 4 months ago 12
Android Question

Android - Change FAB icon when an element into ListView is clicked

I have a

ListView
inside a
Fragment
that contains some songs. When I click on a song, I want to change the icon inside the FAB (that is placed in
Activity
) but I don't know how can I do it. I've tried with this code:

FRAGMENT:

mainActivity = new MainActivity(); //THIS IS INSIDE onCreate METHOD

mListViewSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity.fab.setImageResource(R.drawable.vector_pause);
}
}


I declared my FAB as public inside my Activity, but I still get NullPointerException, how can I solve this problem?

Answer

Assuming your fab is inside your activity, you need a way to communicate between your fragment and you activity. I recommend following this guide this guide.

Essentially, you want to define an interface ActivityController that contains any functions you want to run inside the activity. Here is a mockup example:

ActivityController.java - A new interface you will create

public interface ActivityController {
    void setFabImageResource(int resourceId);
}

MainActivity.java - Modifiy your activity as necessary.

public class MainActivity implements ActivityController {
    //The rest of your code

    public void setFabImageResource(int resourceId) {
        fab.setImageResource(resourceId);
    }
}

YourFragment.java - Just modifiy your fragment like so:

mListViewSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ((ActivityController)getActivity()).setFabImageResource(R.drawable.vector_pause);
        }
    }
Comments