gpt4 book ai didi

android - fragment 创建后触发 ViewPager 监听器

转载 作者:行者123 更新时间:2023-11-30 00:21:41 24 4
gpt4 key购买 nike

短篇小说:

如何在新页面的 fragment 生命周期执行之前检测 ViewPager 页面滚动/更改?

长话短说:

我有一个 ViewPager,其中分配了要使用 ViewPagerAdapter 显示的 fragment ,其中一个 fragment 将根据在寻呼机中选择的当前页面显示不同的数据.

例如,如果当前选择的页面是2,则显示A数据,如果当前选择的页面是4,则显示B数据。

直接的解决方案是使用 OnPageChangeListenerSimpleOnPageChangeListener 根据当前页面设置数据,但两者都不适用,因为正在调用整个生命周期的 fragment 在调用任何这些监听器方法之前,因此将在此处创建 fragment 后设置数据。

第二个直接的解决方案是在接到听众的电话后进行更改,这在用户体验和设计方面非常糟糕。

那么在要执行的 fragment 的 onResume() 方法之前更改 ViewPager 的当前页面时设置 fragment 凭据的最佳方法是什么?


我在做什么:

MyFragment.java中:

// it goes here first
@Override
public void onResume() {
super.onResume();
// check the Data Applied
if(dataA)
doSomething();
else
doSomethingElse();
}

MainActivity.java 中:

pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// then it goes here
// setting the Data of the fragment
if (position == 2)
setDataA();
else (position == 4)
setDataB();
}
});

最佳答案

为什么不使用回调接口(interface)?如果您设置接口(interface),您甚至可以在 fragment onAttach() 或您想要的地方获得回调。

示例实现:

Activity :

public class MyActivity extends AppCompatActivity implements FragmentListener  {

@Override
public void onFragmentSelected(String value) {
// set data here.
}

public interface FragmentListener {
void onFragmentSelected(String value);
}
}

在您的viewPager fragment 中:

public class MyFragment extends Fragment{

@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof MyActivity){
((MyActivity)context).onFragmentSelected("Your_Identification");
}
}
}

在您所有的 viewPager fragment 中执行此操作,这样您就可以从 fragment onAttach() 本身获取附加的 fragment 。或者选择何时调用。

希望对您有所帮助:)

关于android - fragment 创建后触发 ViewPager 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46177185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com