目标是当一个按钮被点击时,图表刷新数据。
我使用了MPAndroidChart,数据绑定布局。
问题是我如何从XML widget id中获取'lineChart‘?
我认为这可能不是实现这一点的正确方法,当单击按钮时刷新图表的更好方法是什么?
xxxViewModel.class
中的代码
fun onButtonClicked() {
// how can I get 'lineChart' from XML widget id?
plotChart(lineChart)
}
fun plotChart(lineChart: LineChart){
//detail code
}
发布于 2021-05-07 08:10:37
我们不应该将视图引用传递给视图模型,这会破坏架构模式。
因此视图将调用viewmodel并执行一些操作VM,然后通过Live data返回数据。
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:onClick="onButtonClicked"
android:paddingEnd="5dp"
android:paddingRight="5dp"
/>
在上面的代码中,有一个xml属性android:onClick
。映射在活动/片段中定义的函数名称(用于单击按钮的操作)。
fun onButtonClicked() {
viewModel.plotChart(lineChart)
}
在上面的方法中,view将调用viewModel
到plotChart
方法来执行操作。
https://stackoverflow.com/questions/67379029
复制相似问题