RecyclerView包含可折叠的TextViews("显示更多" /"显示更少")

时间:2018-06-10 13:51:00

标签: android android-recyclerview

在我的Android应用程序中,我有一个包含TextViews的RecyclerView。如果TextView中的文本超过三行,只有在这种情况下,我想添加一个选项来展开/折叠TextView。

我已经完成了建议的解决方案,普通的textview(getViewTreeObserver()。addOnGlobalLayoutListener,也是布尔值)也与外部库一起使用。我试过了,但最终没有结果。如果有人可以共享代码示例或为其提供建议(特别是在“Recyclerview'”中实现上述内容)将非常有用。提前谢谢。

1 个答案:

答案 0 :(得分:-1)

<强>理论

步骤1.使用MVVM架构,您可以在LiveData<List<*>>中存储2个变量ViewModel

completeDataList =存储完整的数据列表。

shownDataList =您要在RecyclerView中显示的数据列表。您将使用此列表(添加或删除)。

第2步。在Fragment中,获取ViewModel并观察shownDataList。每当值发生变化时,请使用RecyclerView.notifyDataSetChanged()刷新RecyclerView

步骤3.使用TextView.onClickListener命令添加/删除shownDataList内容completeDataList

示例代码

免责声明:这只是一个示例代码,大致展示了它是如何完成的。

MyViewModel.kt

class MyViewModel: ViewModel() {

    val completeDataList = MutableLiveData<List<String>>()
    val shownDataList = MutableLiveData<List<String>>()

    fun initData() {
        //fill your completeDataList with all data
        //Copy three lines to shownDataList
    }

    fun showAll() {
        //Clear and Fill your shownDataList with all data from completeDataList
    }

    fun showLess() {
        //Put only 3 data in your shownDataList
    }
}

MyActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    //After setting the layout, 
    //And also already initialise the RecyclerView along with it's adapter

    myVM = ViewModelProviders.of(this).get(MyViewModel::class.java)
    myVM.shownDataList.observe(this, Observer { newList ->
         if (newList is List<*>) {
             //renewData here is just setting newList 
             //and call notifyDataSetChanged()
             recyclerAdapter.renewData(newList)
         }
    })
    textView.setOnClickListener {
         if (allShown) {
             myVM.showLess()
             allShown = false
         } else {
             myVM.showAll()
             allShown = true
         }
    }
}

希望它有效! :)

相关问题