将View Model实例传递给自定义视图有多安全?会导致内存泄漏吗?从布局中删除视图时,应该将实例设置为null吗?
我也尝试过将View Model实例与数据绑定一起传递,但是代码无法编译。您可以在文章底部看到该示例如何实现数据绑定的示例。
这是创建视图模型并将其传递到自定义视图的方式:
public class MainActivity extends AppCompatActivity {
private MainViewModel mViewModel;
private MainActivityBinding mBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// Pass the application instance, not the activity context
mViewModel = new MainViewModel(getApplication());
createViews();
}
private void createViews() {
// other UI stuff
// ....
addViewWithNames();
}
// Called only at activity onCreate()
private void addViewWithNames() {
// Inflate the custom view
CustomView view = (CustomView) LayoutInflater.from(this).inflate(R.layout.layout_view_names, mBinding.mainLayoutContainer);
// THIS IS WHERE THE VIEW MODEL IS PASSED TO THE VIEW
view.setViewModel(mViewModel);
// Add the view to the bottom of the page
mBinding.linearLayoutBottom.addView(view);
}
// As you can see, there are a couple of different Custom Views, not a single one.
// The Views are getting changed once an action is made in the app
private void addViewWithScores() {
// Inflate the custom view
CustomView view = (CustomView) LayoutInflater.from(this).inflate(R.layout.layout_name_scores, mBinding.mainLayoutContainer);
view.setViewModel(mViewModel);
mBinding.linearLayoutBottom.addView(view);
}
// Random event that can happen
private void onMoveToPage() {
// Is this safe? Will the View Model removed from the Custom View? Will it keep a reference?
mBinding.linearLayoutBottm.removeAllViews();
}
}
下面是带有视图模型实例的自定义视图:
private class CustomView extends RelativeLayout {
private MainViewModel mViewModel;
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setViewModel(MainViewModel viewModel) {
mViewModel = viewModel;
}
// Should I set to null once the View is detached?
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mViewModel = null;
}
}
这是我尝试通过数据绑定传递视图模型的方法,但是在视图膨胀时失败:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="de.nmnm.pager.GameViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- OTHER VIEWS ... -->
<de.nmnm.pager.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:setViewModel="@{viewModel}" />
<!-- OTHER VIEWS ... -->
</LinearLayout>
使用上述数据绑定,项目将编译,创建生成的类,但是当布局膨胀(在活动的onCreate()
时,应用崩溃)。