thusya thusya - 2 months ago 23
Android Question

NavigationDrawer RecyclerView selected items change color

I am trying to change the textColor in my NavigationDrawer when item is selected.I am using RecyclerView as my swipe layout. This is based on the tutorial:

http://www.androidhive.info/2015/04/android-getting-started-with-material-design/

Anyone can suggest the solution

Thanks in Advance.

Answer

Define a static int in NavigationDrawerAdapter class to represent the selected item

In NavigationDrawerAdapter.java

public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
    public static int selected_item = 0;
    ...

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        NavDrawerItem current = data.get(position);
        holder.title.setText(current.getTitle());
        if(position == selected_item)
        {
            holder.title.setTextColor(Color.RED);
        }
        else
        {
            holder.title.setTextColor(Color.BLACK);
        }
    }

    ...

}

In FragmentDrawer.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ...
    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
        @Override
        public void onClick(View view, int position) {

            NavigationDrawerAdapter.selected_item = position;
            recyclerView.getAdapter().notifyDataSetChanged();
            drawerListener.onDrawerItemSelected(view, position);
            mDrawerLayout.closeDrawer(containerView);
        }

        ...
    }));

    ...
}