LiveData观察者与onPrepareOptionsMenu竞赛

时间:2020-01-26 13:35:29

标签: android kotlin android-livedata

我正在研究一个项目,该项目可以使用户成为访客或注册用户。 存在具有当前用户类型的LiveData的应用程序范围google对象

import hashlib
import csv
with open ('C:\Python\Test\Hash.csv') as hash_file:
    # file_reader = csv.DictReader(hash_file)
    file_reader = csv.reader(hash_file)
    # counter = 0
    mydict = dict(filter(None,csv.reader(hash_file)))
    for i in range(1000,10000):
        bank_of_hash = hashlib.sha256(str(i).encode()).hexdigest()
        bank_of_hash={i:bank_of_hash}
    for counter in range(1,11):
        # counter +=1
        if mydict.values() == bank_of_hash.values():     
           print("This is your %s hash and this is the $a your decode" %(i,row))
        else:
            print("Password Not Found!!!")

有一个HomeFragment,需要为注册用户显示user菜单项。 该片段具有绑定到全局属性的ViewModel

private val _isGuest = MutableLiveData<Boolean>()
val isGuest: LiveData<Boolean>
    get() = _isGuest

片段会观察数据

logout

我需要在观察器中切换菜单项,因为注册用户可以在运行时注销,并且当前屏幕将需要分别更新。

问题是我还必须重复onPrepareOptionsMenu中的代码,因为观察者可能会收到通知,val isGuest: LiveData<Boolean> = MainApplication.user.isGuest 菜单在启动时已初始化。 绝对可以将那行代码移到一个单独的函数中,并从两点进行调用,但是没有更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

使用invalidateOptionsMenu()来触发onPrepareOptionMenu()

var menu: Menu? = null

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
...
viewModel.isGuest.observe(viewLifecycleOwner, Observer {
            activity?.invalidateOptionsMenu()//This will trigger onPrepareOptionsMenu
})
}

override fun onPrepareOptionsMenu(menu: Menu) {
this.menu = menu
menu.findItem(R.id.action_logout)?.isVisible = !isGuest
super.onPrepareOptionsMenu(menu)
}