【发布时间】:2020-10-18 06:33:53
【问题描述】:
我有一个FooActivity: AppCompatActivity(),它使用FooViewModel 从数据库中查找Foo,然后在几个Fragments 中显示有关它的信息。以下是我的设置方式:
private lateinit var viewModel: FooViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Get the Intent that started this activity and extract the FOO_ID
val id = intent.getLongExtra(FOO_ID, 1L)
val viewModelFactory = FooViewModelFactory(
id,
FooDatabase.getInstance(application).fooDao,
application)
viewModel = ViewModelProviders.of(
this, viewModelFactory).get(FooViewModel::class.java)
// FooViewModel is bound to Activity's Fragments, so must
// create FooViewModelFactory before trying to bind/inflate layout
binding = DataBindingUtil.setContentView(this, R.layout.activity_foo)
binding.lifecycleOwner = this
binding.viewModel = viewModel
}
在FooInfoFragment 类中:
private val viewModel: FooViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
val binding = FragmentFooInfoBinding.inflate(inflater)
binding.setLifecycleOwner(this)
binding.viewModel = viewModel
// normally viewModel.foo shouldn't be null here, right?
return binding.root
}
到目前为止一切顺利。我的布局显示了Foo 的各种信息,例如@{viewModel.foo.name}。
问题是在我的FooInfoFragment.onCreateView 中,当我在绑定后尝试访问viewModel.foo.value?.name 时,viewModel 为空。
binding.viewModel = viewModel
Log.wtf(TAG, "${viewModel.foo.value?.name} shouldn't be null!")
return binding.root
我不明白为什么它在我的 Fragment 中为空,但在我的布局中却没有。帮忙?
【问题讨论】:
-
activityViewModels()(我想这是来自 fragemnt-ktx )有自己的实现我认为它无法创建一个,因为你有一个参数化的构造函数。 -
@ADM 我知道 viewModel 正在创建
by activityViewModels(),因为我看到绑定后Foo信息在Fragment布局中呈现。activityViewModels()使用ViewModelFactory创建ViewModel。见codelabs.developers.google.com/codelabs/… -
视图模型真的是空的吗?在
viewModel.foo.value?.name行中,也可以是foo或foo.value。如果是viewmodel或viewModel.foo,应用就会崩溃。 -
viewModel本身为空?还是viewModel.foo.value?.name为空?如果viewModel.foo.value则可能是因为尚未设置实时数据。也就是尚未加载数据库中的数据。
标签: android kotlin layout fragment viewmodel