50

我使用 ViewPager 通过左/右滑动来切换视图。

ViewPager 需要一个适配器,所以我构建了这个:

public class ListViewPagerAdapter extends PagerAdapter {

protected static final String TAG = "ListViewPagerAdapter";
protected static final int NUM_VIEWS = 3;

protected final Activity mActivity;

public ListViewPagerAdapter(Activity activity) {
    mActivity = activity;
}

@Override
public int getCount() {
    return NUM_VIEWS;
}

@Override
public void startUpdate(View container) {}

@Override
public Object instantiateItem(View container, int position) {
    // ViewPager
    ViewPager viewPager = (ViewPager) container;

    // Wird verwendet, um die Views aufzurufen
    LayoutInflater layoutInflater = mActivity.getLayoutInflater();

    // Standardmäßig ist news eingeblendet
    View view = layoutInflater.inflate(R.layout.news_fragment, null);
    // Falls sich die Position verändert, so verändert sich auch die View
    if (position == 0) {
        view = layoutInflater.inflate(R.layout.favorite_fragment, null);
    } else if (position == 2) {
        view = layoutInflater.inflate(R.layout.videos_fragment, null);
    }

    // View einblenden
    viewPager.addView(view, 0);

    return view;
}

@Override
public void destroyItem(View container, int position, Object object) {
    // ViewPager
    ViewPager viewPager = (ViewPager) container;
    // View
    View view = (View) object;

    // View löschen
    viewPager.removeView(view);
}

@Override
public void finishUpdate(View container) {}

@Override
public boolean isViewFromObject(View view, Object object) {
    View _view = (View) object;
    return view == _view;
}

@Override
public Parcelable saveState() {
    return null;
}

@Override
public void restoreState(Parcelable state, ClassLoader loader) {}
 }

现在,我想通过 viewpager 获取当前的焦点视图。我尝试了 getChildAt(x),但它不起作用。

有没有一些例子,或者你知道如何获得当前视图?

谢谢

4

11 回答 11

89

可以通过重写PagerAdapter.setPrimaryItem方法来保存当前活动的对象(视图、片段...) 。例如:

private View mCurrentView;

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    mCurrentView = (View)object;
}
于 2011-12-26T20:01:48.813 回答
41

您可以在 instantiateItem 方法中为创建的视图添加标签:

view.setTag(position);

稍后您可以通过以下方式访问当前选定的视图:

mPager.findViewWithTag(mPager.getCurrentItem());
于 2012-06-24T09:57:27.663 回答
41

您必须注册一个监听器到您的ViewPager

pager.setOnPageChangeListener(new MyPageChangeListener()); 

您必须通过扩展存根侦听器来自定义侦听器:

private int focusedPage = 0;
private class MyPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
    @Override
    public void onPageSelected(int position) {
        focusedPage = position;
    }
}

我通过查看兼容性库中的 ViewPager.java 源代码发现了这一点。我读到我们可以做更多,例如 catch onPageScrollStateChanged

为了构建适配器,我使用了这篇博文中的代码。你可能想看看。

于 2011-07-25T16:48:27.713 回答
4

我最近需要实施这个确切的解决方案。这是我的做法:

Map<Integer, Object> views = Maps.newHashMap();

@Override
public Object instantiateItem(View container, int position) {
  /* Create and add your View here */
  Object result = ???

  views.put(position, result);
  return result;
}

@Override
public void destroyItem(View container, int position, Object object) {
  /** Remove your View here */

  views.remove(position);
}

protected View findViewForPosition(int position) {
  Object object = views.get(position);
  if (object != null) {
    for (int i = 0; i < getChildCount(); i++) {
      View view = getChildAt(i);
      if (isViewFromObject(view, object)) {
        return view;
      }
    }
  }
  return null;
}
于 2011-11-08T15:13:23.620 回答
2

尝试这个:

public View getCurrentView(ViewPager pager) {
    for (int i = 0; i < pager.getChildCount(); i++) {
        View child = pager.getChildAt(i);
        if (child.getX() <= pager.getScrollX() + pager.getWidth() && 
            child.getX() + child.getWidth() >= pager.getScrollX() + pager.getWidth()) {
            return child;
         }
     }
     return getChildAt(0);
}
于 2012-11-20T05:23:40.000 回答
1

为了获得焦点视图,我使用这种方式:

当我在将视图添加到 ViewPager 之前膨胀视图时,我为其设置了标签。然后我检查这个标签。

private View getCurrentView()
{
    for (int i = 0; i < pager.getChildCount(); i++)
    {
        View v = pager.getChildAt(i);
        if (v != null)
        {
            if (v.getTag().equals(pageList.get(pager.getCurrentItem()).getTag())) return v;
            // pageList is a list of pages that I pass to page adapter
        }
    }
    return null;
}
于 2012-02-14T11:02:41.530 回答
0

给出的答案并不适合我,它们都有不想要的副作用。要么我必须添加不必要的变量(我喜欢干净的代码),要么我必须解决 Android 框架本身。

我的解决方案是基于反射,它访问ViewPager中所有对象的数组列表,并返回ViewPager中当前选中的对象。它几乎没有副作用(反射很慢,是现有类的子类化)并且它保持代码干净。

public class ViewPagerEx extends ViewPager {

    private static final String TAG = ViewPagerEx.class.getSimpleName();

    public ViewPagerEx(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewPagerEx(Context context) {
        super(context);
    }

    public Object getCurrentObject() {
        try {
            final Field itemsField = ViewPager.class.getDeclaredField("mItems");
            itemsField.setAccessible(true);

            final ArrayList<Object> items = (ArrayList<Object>) itemsField.get(this);

            final int currentItemIndex = getCurrentItem();
            if (currentItemIndex < 0 || currentItemIndex >= items.size()) {
                return null;
            }

            final Object infoItem = items.get(getCurrentItem());

            final Class<?> itemInfoClass = findItemInfoClass(ViewPager.class.getDeclaredClasses());

            final Field objectField = itemInfoClass.getDeclaredField("object");
            objectField.setAccessible(true);
            return objectField.get(infoItem);

        } catch (NoSuchFieldException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.toString());
        }

        return null;
    }

    private Class<?> findItemInfoClass(final Class<?>[] classes) throws IllegalArgumentException {
        for (int i = 0; i < classes.length; i++) {
            if (classes[i].getSimpleName().equals("ItemInfo")) {
                return classes[i];
            }
        }

        throw new IllegalArgumentException("cannot find class ItemInfo");
    }
}
于 2012-08-17T14:50:06.993 回答
0

您可以使用:

 viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            Log.i("maylonsales", "onPageSelected position " + position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
于 2020-03-27T17:44:04.347 回答
0

在你的内部FragmentStatePagerAdapter

    private View mCurrentView;

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment f = (Fragment) object;
        mCurrentView = f.getView();
    }
于 2016-03-17T18:37:32.103 回答
-1

如果仔细检查,ViewPager 最多保存 3 个视图。您可以通过以下方式轻松获取当前视图

view     = MyActivity.mViewPager.getChildAt(1);
于 2012-12-12T22:12:54.890 回答
-1

我错过了什么吗?ViewGroup 中只有 3 个孩子,所以归结为:

int current = viewPager.getCurrentItem();
int childCount = viewPager.getChildCount();
// If there's a single page or we're at the beginning, return the first view
if (childCount == 1 || current == 0) {
  return viewPager.getChildAt(0);
} else { //For any other case, we want the second child. This is either the last page or the page in the middle for any other case.
  return viewPager.getChildAt(1);
}
于 2014-01-09T00:29:05.330 回答