android-如何观察ankocomponent中的viewmodel

时间:2019-01-09 00:52:40

标签: kotlin fragment viewmodel anko anko-component

我想在anko组件中使用viewmodelproviders

我研究了Google开发人员指南中的Viewmodel文档,但未记录此特定用例

class BroadcastCalendarFragment: Fragment() 
{
  lateinit var mBroadcastModel: BroadcastModel

  override fun onCreateView(inflater: LayoutInflater, container: 
  ViewGroup?, savedInstanceState: Bundle?): View? {
        return BroadcastCalendarUI<Fragment>().createView(AnkoContext.create(ctx, this))
    }
}

class BroadcastCalendarUI<BroadcastCalendarFragment>(): AnkoComponent<BroadcastCalendarFragment>
{

    lateinit var broadcastModel: BroadcastModel

    override fun createView(ui: AnkoContext<BroadcastCalendarFragment>): View = with(ui) {
    verticalLayout{
      button.setOnclickListener{
      broadcastModel = ViewModelProviders.of(BroadcastCalendarFragment()).get(BroadcastModel::class.java)

      }
   } 
  }
}

如果我单击按钮,则会显示错误消息

java.lang.IllegalStateException:无法为分离的片段创建ViewModelProvider

(它在我在点击侦听器中使用ViewModelProviders(BroadcastCalendarFragment()的那一行显示)

1 个答案:

答案 0 :(得分:0)

 ViewModelProviders.of(BroadcastCalendarFragment())

正在创建一个新的BroadcastCalendarFragment,并尝试从中查找/创建视图模型。问题在于,这个新片段未附加到任何活动,为此ViewModelProviders无法找到合适的提供者。

您应该能够使用

找到合适的片段实例
ViewModelProviders.of(owner).get(BroadcastModel::class.java)