我正在使用布尔值更新片段中的视图。
从片段开始工作,但是活动中有代码触发布尔值,但是直到我再次手动进入片段之前,视图都无法更新。
活动代码:
billingClientLifecycle.purchaseUpdateEvent.observe(this, Observer {
it?.let {
Log.d("King", "John it 1$it")
registerPurchases(it)
subbed = if (it.isEmpty()) {
Log.d("King", "inside empty")
false
} else {
Log.d("King", "inside not empty")
true
}
}
})
片段代码
if (subbed){
Log.d("King", "insideifsubbed$subbed")
matchesBinding.homeBasicMessage.visibility = View.VISIBLE
matchesBinding.homePaywallMessage.visibility = View.GONE
matchesBinding.homeAccountHoldMessage.visibility = View.GONE
matchesBinding.homeTransferMessage.visibility = View.GONE
}else{
matchesBinding.homeBasicMessage.visibility = View.GONE
matchesBinding.homeAccountHoldMessage.visibility = View.GONE
matchesBinding.homeTransferMessage.visibility = View.GONE
matchesBinding.homePaywallMessage.visibility = View.VISIBLE
Log.d("King", "insideelsesubbed$subbed")
}
答案 0 :(得分:1)
在您的Fragment
中实现侦听器,以便您的Activity
每次想要更新任何新信息时都可以向其发送回调。
例如,您可以创建
interface SubbedUpdateListener {
fun onSubUpdate(subbed: Boolean)
}
并实现相关字段和设置器
var mSubbedUpdateListener: SubbedUpdateListener? = null; private get
fun setSubbedUpdateListener(subbedUpdateListener: SubbedUpdateListener){
mSubbedUpdateListener = subbedUpdateListener
}
最后是调用代码:
billingClientLifecycle.purchaseUpdateEvent.observe(this, Observer {
it?.let {
Log.d("King", "John it 1$it")
registerPurchases(it)
subbed = if (it.isEmpty()) {
Log.d("King", "inside empty")
false
} else {
Log.d("King", "inside not empty")
true
}
if(mSubbedUpdateListener != null){
mSubbedUpdateListener.onSubUpdate(subbed)
}
}
})
在Activity
内部,并在Fragment
或onAttach
方法内部创建新的onCreate
时,可以使用传入的context
,这应该是您的调用Activity
,将其强制转换为Activity
类,如果您对activity.setSubbedUpdateListener(this)
使用Fragment
,则调用implements SubbedUpdateListener
。否则,您也可以传入SubbedUpdateListener
的匿名或命名实例。在实施过程中,您可以检查:
override fun onSubUpdate(subbed: Boolean){
if (subbed){
Log.d("King", "insideifsubbed$subbed")
matchesBinding.homeBasicMessage.visibility = View.VISIBLE
matchesBinding.homePaywallMessage.visibility = View.GONE
matchesBinding.homeAccountHoldMessage.visibility = View.GONE
matchesBinding.homeTransferMessage.visibility = View.GONE
}else{
matchesBinding.homeBasicMessage.visibility = View.GONE
matchesBinding.homeAccountHoldMessage.visibility = View.GONE
matchesBinding.homeTransferMessage.visibility = View.GONE
matchesBinding.homePaywallMessage.visibility = View.VISIBLE
Log.d("King", "insideelsesubbed$subbed")
}
}
编辑:对不起。刚刚意识到您在Kotlin上的写作,而我正在用Java编写示例。
答案 1 :(得分:0)
这是因为片段已经创建,并且没有人观察到子变量的变化。将subbed布尔值设置为boolean类型的实时数据,然后在activity中设置值,并观察片段中的subbed值。
keybindings.json
val subbed : MutableLiveData<Boolean> = MutableLiveData()
billingClientLifecycle.purchaseUpdateEvent.observe(this, Observer {
it?.let {
Log.d("King", "John it 1$it")
registerPurchases(it)
subbed.value = if (it.isEmpty()) {
Log.d("King", "inside empty")
false
} else {
Log.d("King", "inside not empty")
true
}
}
})