利用RecyclerView实现自己的类似于ExpandableListView效果

关于RecyclerView总感觉有许多要说的,但是又不知道从什么地方说起,今天这个不是我的第一篇关于RecyclerView上的文章,但是是我第一篇发表的,起个引子作用:
公司在项目中要实现一个类似于expandablelistview效果的控件,但是我已经开始使用recyclerview,不想用listview,然后就走上了踩坑之路了。

源码地址
最开使用的是国外培训机构出品的一个控件,但是感觉很繁琐,实现起来有问题,就自己重写了一个实现,这篇文章简单的介绍代码,没有将原理。

看一下效果图:

上代码:

1. 首先来看一下布局文件

fragment_history.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.saka.myapplication.Fragment.HistoryFragment">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="历史上的今天"
            android:textSize="30sp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="20sp"/>
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_history"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>


    </LinearLayout>
</layout>

假如不熟悉Databinding的朋友可以去看看我的另一篇文章

DataBinding(一)-初识

布局文件很简单,有用的只有这个recyclerview,其他的都没用。

2. 布局文件的java代码

这里是一些常规化的代码。

 /**
     * 初始化RecyclerView
     */
    private void initViews() {
        binding.rvHistory.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.rvHistory.setItemAnimator(new NoAlphaItemAnimator());
        adapter = new HistoryAdapter(getActivity(), results);
        adapter.setItemClickListener(this);
        binding.rvHistory.setAdapter(adapter);
        startRequest();
    }

首先是setlayoutManager,此处我用的是垂直的布局。

然后是setItemAnimator,这个是重点,同学们要好好记。

然后是adapter,这个是实现的具体方法。一会重点讲。

startrequest是请求数据的方法,用来更新数据。

3. 看一下item的布局文件(稍微复杂)

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="historymodel"
            type="com.saka.myapplication.Models.HistoryModle.HistoryResult" />
    <variable
        name="historyclickevent"
        type="com.saka.myapplication.Models.SearchItemClick"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:gravity="center"
            android:paddingBottom="10dp"
            android:onClick="@{()->historyclickevent.onClickItem()}"
            android:text="@{historymodel.title}"
            android:textColor="@color/textwhite"
            android:textSize="20sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:visibility="@{historymodel.showDetails}">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="时间:"
                    android:textColor="@color/colorAccent"
                    android:textSize="15sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{historymodel.date}"
                    android:textSize="15sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="农历:"
                    android:textColor="@color/colorAccent"
                    android:textSize="15sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@{historymodel.lunnar}"
                    android:textSize="15sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="事件:"
                    android:textColor="@color/colorAccent"
                    android:textSize="15sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@{historymodel.des}"
                    android:textSize="15sp" />
                    
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</layout>

生成的布局文件大概是这样的:

共包含三个部分,首先是标题部分,就是那个浅蓝色,虽然没什么内容都没有,但是请求到内容后就会显示文字了。

下面部分 时间、农历、事件 是需要隐藏的部分。

4 HistoryHolder内容

此处要注意databing的写法。上边的链接有详细介绍

static class HistoryHolder extends RecyclerView.ViewHolder {
        ViewDataBinding binding;
        public HistoryHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        static HistoryHolder createViewHolder(ViewGroup container, int layoutId) {
            ViewDataBinding binding = DataBindingUtil.inflate(
                    LayoutInflater.from(container.getContext()), layoutId, container, false);
            return new HistoryHolder(binding);
        }
    }

这个viewholer是一个通用的holder,是传参数传进来item布局文件的id int layoutId

5. HistoryAdapter文件

关于adapter要复写的几个方法主要讲这个onBindViewHoler方法:

 @Override
    public void onBindViewHolder(HistoryHolder holder, int position) {
        holder.binding.setVariable(BR.historymodel, historyResults[position]);
        searchItemClick=new SearchItemClick(position);
        searchItemClick.setListener(listener);
        holder.binding.setVariable(BR.historyclickevent,searchItemClick);
        holder.binding.executePendingBindings();

    }

这个地方的historymodel对应item布局文件中的variable中的
name="historymodel" type="com.saka.myapplication.Models.HistoryModle.HistoryResult" />

这个searchItemClick是一个点击事件,用来传递position参数

在Historyfragment实现了这个接口,用来隐藏/显示detail(详细内容)。

 @Override
    public void onItemClick(int resId) {
        Log.d("fff", "点击了事件" + resId);
        if (results[resId].getShowDetails() == View.GONE) {
            Log.d("fff", "显示条目");
            results[resId].setShowDetails(View.VISIBLE);
        } else {
            Log.d("fff", "隐藏条目");
            results[resId].setShowDetails(View.GONE);
        }
        adapter.notifyItemChanged(resId);
    }

此时打开应用可以看到这个时候已经可以简单的扩展收缩了

但是看清楚,在现实detail的时候效果还可以,但是隐藏detail的时候就非常蛋疼了,是下边的item完全上去之后detail的内容才会隐藏,这就很难受了。

这个时候要研究一下recyclerview的动画机制。在你不给recyclerview添加动画时,adapter.notifyItemChanged()方法会出发recyclerview的动画,一般有个默认的DefaultItemAnimator()动画。我们要做的就是重写这类,做成我们想要的动画效果。

我新建了一个动画类叫NoAlphaItemAnimator,此处我要实现的是在点击后改变item的高度,而不是删除或者添加,我们需要找到这个内部类,private static class ChangeInfo。
它就是在改变item时调用的动画,然后找到void animateChangeImpl(final ChangeInfo changeInfo)这个方法,找到里边的实现方法 public void onAnimationStart(View view)
在下边添加

 if (view.findViewById(history_more).getVisibility() == View.GONE) {
                        AlphaAnimation animation = new AlphaAnimation(0, 1);
                        animation.setDuration(300);
                        view.findViewById(history_more).startAnimation(animation);
                    } else {
                        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
                        alphaAnimation.setDuration(300);
                        view.findViewById(history_more).startAnimation(alphaAnimation);
                        view.findViewById(history_more).setVisibility(View.GONE);
                    }

添加如上代码,就可以实现隐藏了。
看一下效果:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容