【问题标题】:How to update activity views from a fragment recyclerView如何从片段 recyclerView 更新活动视图
【发布时间】:2019-12-20 15:53:07
【问题描述】:

我有 MainActivity,它有 AppBar(带有“购物车”TextView)和 FrameLayout(带有包含 RecyclerView 的 Fragment)。这个 RecyclerView 有一个增加购物车值计数的按钮。我希望该计数能够更新 MainActivity 中的购物车值。

我找到了这个,但没有完整的解释“Updating views of Activity or Fragment from a RecyclerView adapter”。

【问题讨论】:

    标签: android-activity android-recyclerview


    【解决方案1】:

    没有比这个ViewModel更好的解决方案了

    首先在build.gradle中添加这个依赖:implementation 'android.arch.lifecycle:extensions:1.1.1'

    您的ViewModel 课程将如下所示:

    class MyViewModel: ViewModel() {
    
        val mCartInfo: MutableLiveData<Int> = MutableLiveData()
        private var cnt = 0
    
        fun addToCartCounter() {
            //TODO Apply your logic here
            mCartInfo.value = cnt++
        }
    }
    

    LiveData 是什么? See here

    之后你必须初始化你的ViewModel并观察变化的数据,所有这些都将在你的AppBar的Activity中完成:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val myViewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
            //These will observe any changes happen in ViewModel's MutableLiveData(it'll directly jump inside Observer)
            //Observer is main important thing
            myViewModel.mCartInfo.observe(this, Observer {
                //tvCartCounter is Toolbar's TextView
                tvCartCounter.text = it.toString()
            })
        }
    }
    

    在您的Fragment 中获取ViewModel,然后单击调用ViewModel 方法的按钮:

    class BlankFragment : Fragment() {
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            // Inflate the layout for this fragment
            val rootView = inflater.inflate(R.layout.fragment_blank, container, false)
    
            //Get your Activity's ViewModel
            val myViewModel = ViewModelProviders.of(requireActivity()).get(MyViewModel::class.java)
            //Button click
            rootView.btnAddToCart.setOnClickListener {
                //It'll call ViewModel's method
                myViewModel.addToCartCounter()
            }
            return rootView
        }
    }
    

    每当addToCartCounter() 调用您的按钮单击时,它会在触发您的观察者后不久在MutableLiveData 中添加值。

    【讨论】:

    • 能否请您给出更详细的答案,我很难理解。
    • 我已经编辑了我的答案,请检查并通知我。祝你有美好的一天:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多