Android liveData与viewBinding使用教程
目录
- ViewModel
- liveData
- viewBinding
ViewModphpel
官方解释:保存UI数据的类,会在配置变更(如手机屏幕的旋转)后继续存在。
view Model不应持有context,否则在Activity销毁后View Model仍然持有Activity的context,造成内存泄漏;可以继承ANIiRrBSGondroidViewModel,或者选择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数据
p编程客栈rivate TestViewModel vm; @Override protected void onCreate(Bundle savedInstanceState) { s开发者_JAVA入门uper.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, php ViewGroup container, Bundle savedInstanceState) { js ActivityMainBinding binding = ResultProfileBinding.inflate(inflater, container, false); View view = binding.getRoot(); return view; }
由于fragment的生命周期更长,所以务必在destroy解除绑定
@Override public void onDestroyView() { super.onDestroyView(); binding = null; }
到此这篇关于android liveData与viewBinding使用教程的文章就介绍到这了,更多相关Android liveData与viewBinding内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论