我正在构建一个使用ViewPager和FragmentStatePagerAdapter一次显示多个片段的应用程序。以下是我在做什么:
public class PageViewActivity extends FragmentActivity {
protected static final String TAG = "PageViewActivity";
MyPageAdapter pageAdapter;
private List<Fragment> fragments;
private FragmentManager fragmentManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page_view);
fragments = getFragments();
fragmentManager = getSupportFragmentManager();
pageAdapter = new MyPageAdapter(fragmentManager, fragments);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Log.i(TAG, "Inside onPageSelected....................... "
+ position);
((MyFragment) pageAdapter.getChildAt(position)).updateView();
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.i(TAG, "Inside onPageScrolled... " + arg0);
}
@Override
public void onPageScrollStateChanged(int arg0) {
Log.i(TAG, "Inside onPageScrollStateChanged... " + arg0);
}
});
}
private List<Fragment> getFragments() {
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragment.newInstance("Fragment 1"));
fList.add(MyFragment.newInstance("Fragment 2"));
fList.add(MyFragment.newInstance("Fragment 3"));
fList.add(MyFragment.newInstance("Fragment 4"));
fList.add(MyFragment.newInstance("Fragment 5"));
fList.add(MyFragment.newInstance("Fragment 6"));
fList.add(MyFragment.newInstance("Fragment 7"));
return fList;
}
private class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
public void setList(List<Fragment> fragments) {
this.fragments = fragments;
notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
Log.i(TAG, "Inside getItem............");
return this.fragments.get(position);
}
@Override
public int getCount() {
return this.fragments.size();
}
@Override
public float getPageWidth(int position) {
if (position == 0) {
return 0.4f;
} else {
return 0.3f;
}
}
public Fragment getChildAt(int position) {
return this.fragments.get(position);
}
@Override
public int getItemPosition(Object object) {
Log.i(TAG, "getItemPosition..........");
if (fragments.contains(object)) {
Log.i(TAG,
"fragmentList.contains(object)... " + object.toString());
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
}
}
}
我的问题是如何找到可见的碎片? (例如,屏幕截图中的片段1、2和3)
我知道abot pager.setOnPageChangeListener和Fragment.setUserVisibleHint(boolean isVisibleToUser)但对我没有用:-(
非常感谢您的帮助。谢谢!!!
最佳答案
这个link可能会有所帮助
使用这一行代码Fragment fr = getSupportFragmentManager().findFragmentByTag(“android:switcher:” + R.id.pager + “:” + mViewPager.getCurrentItem());