Android点击无颜色变化?可能是ViewModel生命周期惹的祸

android 点击后颜色无变化原因分析

在android开发中,使用viewmodel来管理ui数据时,经常会遇到点击后颜色无变化的情况,这可能是由于以下原因造成的:

生命周期所有者未设置

引用viewmodel时,需要设置它的生命周期所有者,以确保在生命周期改变时更新绑定数据。在上述代码中,生命周期所有者未设置,导致视图无法收到viewmodel数据的更新。

解决方案

在fragment的oncreateview()方法中,设置生命周期所有者:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    this.binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
    // 设置生命周期所有者
    this.binding.setLifecycleOwner(this);
    r

eturn this.binding.getRoot(); }