android fragment setuservisiblehint,in androidx.fragment.app.Fragment,setUserVisibleHint()is Depreca...

本文介绍了AndroidX中`setUserVisibleHint()`方法的废弃,并推荐使用`setMaxLifecycle()`来管理Fragment生命周期。讲解了如何用新的构造函数行为和Lifecycle状态来替换旧方法,并提供了相关链接以获取更多详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

@Override

public void setUserVisibleHint(boolean isVisibleToUser) {

super.setUserVisibleHint(isVisibleToUser);

if (getUserVisibleHint()) {

isVisible = true;

onVisible();

} else {

isVisible = false;

onInVisible();

}

}

I found that this part of the code is not executed.

回答1:

Now in AndroidX method setUserVisibleHint(boolean isVisibleToUser) is deprecated and if you take a look into documentation, it says:

You can now set a max Lifecycle state for a Fragment by calling

setMaxLifecycle() on a FragmentTransaction. This replaces the now

deprecated setUserVisibleHint(). FragmentPagerAdapter and

FragmentStatePagerAdapter have a new constructor that allows you to

switch to the new behavior.

So basically when you use this approach in FragmentTransaction:

.getSupportFragmentManager()

.beginTransaction()

.setMaxLifecycle(fragment, Lifecycle.State.STARTED);

would be equivalent to setUserVisibleHint(false) and:

.getSupportFragmentManager()

.beginTransaction()

.setMaxLifecycle(fragment, Lifecycle.State.RESUMED);

would be equivalent to: setUserVisibleHint(true)

回答2:

They just changed API in Fragments.

If you use this method to limit fragments lifecycle:

You can now set a max Lifecycle state for a Fragment by calling

setMaxLifecycle() on a FragmentTransaction. This replaces the now

deprecated setUserVisibleHint().

Source: https://developer.android.com/jetpack/androidx/releases/fragment#1.1.0-alpha07 .

If you need this method because you try to detect which fragment is currently visible in ViewPager. You can now just use onResume and onPause methods instead but before that you should change default behaviour in FragmentPagerAdapter constructor.

Like this:

FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

来源:https://stackoverflow.com/questions/57885849/in-androidx-fragment-app-fragment-setuservisiblehint-is-deprecated-and-not-exec

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值