短篇小说:
如何在新页面的片段生命周期执行之前检测ViewPager
页面滚动/更改?
长篇故事:
我有ViewPager
分配的片段要使用ViewPagerAdapter
显示,其中一个片段根据寻呼机中选择的当前页面显示不同的数据。
例如,如果选择的当前页面为 2 ,则会显示 A 数据,如果选择的当前页面为 4 ,则会显示 B 数据。
直接的解决方案是使用OnPageChangeListener
或SimpleOnPageChangeListener
根据当前页面设置数据,但两者都不适用,因为片段在任何这些侦听器方法之前调用了生命周期被调用,所以数据将在片段创建后设置。
第二个直接的解决方案是在收到来自听众的电话后进行更改,这对于用户体验和设计非常糟糕。
在更改要执行的片段的ViewPager
方法之前onResume()
的当前页面时,设置片段凭据的最佳方法是什么?
我在做什么:
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();
}
});
答案 0 :(得分:1)
为什么不使用回调接口?如果您设置了界面,您甚至可以在片段onAttach()
或您想要的位置接听回电。
示例实施:
<强>活动强>:
public class MyActivity extends AppCompatActivity implements FragmentListener {
@Override
public void onFragmentSelected(String value) {
// set data here.
}
public interface FragmentListener {
void onFragmentSelected(String value);
}
}
在您的viewPager
碎片:
public class MyFragment extends Fragment{
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof MyActivity){
((MyActivity)context).onFragmentSelected("Your_Identification");
}
}
}
在所有viewPager
片段中执行此操作,以便从片段onAttach()
本身获取附加的片段。或者选择应该何时调用。
希望它有助于:)