我正在使用一个很棒的库:Alerter。我在ViewPager中有3个片段。当我显示一个片段时,我想用这个库显示一个Alert。但是,警报第一次没有显示。当我点击一个按钮显示一个新按钮时,第一个按钮会在第二个按钮后退出并按下该按钮。就像警报延迟到请求新警报一样。
这是我用于主片段的ocde:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
final MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle) adapter.getItem(position);
fragmentToShow.onResumeFragment();
}
});
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Cube", "Osselet", "Watch"};
private MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
// Return Map Fragment
if (position == 0) {
return new RecordCubeFragment();
}
//Return Toilet List Fragment
else if (position == 1) {
return new RecordOsseletFragment();
}
else if (position == 2) {
return new RecordWatchFragment();
}
else {
return new RecordCubeFragment();
}
}
ViewPager中有一个子片段的代码:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "call oncreateview");
View v = inflater.inflate(R.layout.fragment_record_cube, container, false);
lectureButton = (ImageButton) v.findViewById(R.id.lectureButton);
return v;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "call onview created");
super.onViewCreated(view, savedInstanceState);
lectureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("second alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
});
Alerter.create(getActivity())
.setTitle("Warning !")
.setText("first alert.")
.setIcon(R.drawable.alert_icon)
.setBackgroundColorInt(Color.RED)
.setDuration(2000)
.show();
}
对于帮助,我知道ViewPager中的片段生命周期是不同的,这就是为什么我实现了一个OnPageChangeListener,但我无法摆脱这个问题。