Android的RecyclerView选择第一项 [英] Android RecyclerView select first Item

查看:3738
本文介绍了Android的RecyclerView选择第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是RecyclerView实现NavigationDrawer。

I'm using a RecyclerView to implement a NavigationDrawer.

我得到了点击事件的工作,但我无法弄清楚如何对应用程序启动和保持均匀亮显选定的项目,如果没有显示抽屉下面所选择的第一个项目。

I got click events working, but I can't figure out how to have the first item selected on App start and following that keep the selected item higlighted even if the drawer is not shown.

所有我能找到是多选在RecyclerView。

All I've been able to find is multi-selection in RecyclerView.

推荐答案

我其实只是一个应用程序我工作实现了这个。所以此方法处理:

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;

然后在你的适配器的构造函数初始化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;
    }

下面我用0,因为这是在我的菜单中的第一项。

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

然后在你的 onBindViewHolder(NavDrawerMenuListViewHolder持有人,INT位置)只是检查是否你的将selectedItem ==位置并集一些人认为的背景下,像这样一个背景入围:

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);
        } 

在这里我设置文本​​颜色为绿色,并给予Realativelayout父在启动一个灰色背景。当然,你可以的,你喜欢的任何方式定制的。

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);

    }

这个方法我通常的OnClick()方法调用。

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

希望这有助于!

这篇关于Android的RecyclerView选择第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆