Android RecyclerView select first Item

流过昼夜 提交于 2019-12-01 18:05:51

I actually just implemented this in an app I am working on. So this method worked:

First create a variable to track the current selected position at the top of your adapter:

private int selectedItem;

Then in your Adapter constructor initiate the selectedItem value you would like:

public NavDrawerMenuListAdapter(Context context, List<NavDrawerItem> data, NavDrawerMenuListViewHolder.NavDrawerMenuClickInterface listener) {
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
        this.navDrawerItems = data;
        this.listener = listener;
        selectedItem = 0;
    }

Here I use 0 as this is the first item in my menu.

Then in your onBindViewHolder(NavDrawerMenuListViewHolder holder, int position) just check whether your selectedItem == position and set the background of some view to a seleted background like so:

if (selectedItem == position) {
            holder.single_title_textview.setTextColor(0xff86872b);
            holder.nav_drawer_item_holder.setBackgroundColor(Color.DKGRAY);
        } 

Here I set the text color to green and give the Realativelayout parent a gray background on start. You can, of course, customize this in any way you like.

To implement a selection of an item and keep the state I use the following method:

public void selectTaskListItem(int pos) {

        int previousItem = selectedItem;
        selectedItem = pos;

        notifyItemChanged(previousItem);
        notifyItemChanged(pos);

    }

This method I usually call from the OnClick() method.

Hope this helps!.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!