亲宝软件园·资讯

展开

Android liveData与viewBinding使用教程

Flynn_MIMD 人气:0

ViewModel

官方解释:保存UI数据的类,会在配置变更(如手机屏幕的旋转)后继续存在。

view Model不应持有context,否则在Activity销毁后View Model仍然持有Activity的context,造成内存泄漏;可以继承AndroidViewModel,或者选择application context

liveData

1.建立data类

public class Time {
    private MutableLiveData<Integer> seconds = new MutableLiveData<>();
    public MutableLiveData<Integer> getSeconds() {
        return seconds;
    }
}

2.继承View Model

public class TestViewModel extends ViewModel {
    private Time time;
    public TestViewModel(){
        time = new Time();
        // 修改liveData包装的数据,主线程用setValue,其他线程PostValue
        time.getSeconds().setValue(0);
    }
    public Time getLiveData(){
        return time;
    }
}

3.observe数据

private TestViewModel vm;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    vm = new TestViewModel();
    vm.getLiveData().getSeconds().observe(this, new Observer<Integer>() {
        @Override
        public void onChanged(Integer integer) {
            EditText ed = findViewById(R.id.ed);
            ed.setText(""+integer);
        }
    });

viewBinding

1.build.gradle添加

buildFeatures {
    viewBinding true
}

根视图和所有有ID的视图都会根据xml文件名称,生成对应的Binding类

2. 在Activity中使用view Binding

ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);

如果找不到Binding类,可能是名字错了,顺序再调一下可能就对了

在Fragment中使用view Binding

 @Override
    public View onCreateView (LayoutInflater inflater,
                              ViewGroup container,
                              Bundle savedInstanceState) {
        ActivityMainBinding binding = ResultProfileBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        return view;
    }

由于fragment的生命周期更长,所以务必在destroy解除绑定

@Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

加载全部内容

相关教程
猜你喜欢
用户评论