ViewPager获取当前显示的View[通俗易懂]

ViewPager获取当前显示的View[通俗易懂]//获取-vp当前childpublicstaticViewgetCurChild_vp(ViewPagervp){intchildCnt=vp.getChildCount();inttotalCnt=vp.getAdapter().getCount();intcurItem=vp.getCurrentItem();inttarg

大家好,又见面了,我是你们的朋友全栈君。

思路:根据vp.getCurrentItem一级vp的child数,可算出当前child在vp中的index。但是此时还不能直接用vp.getChildAt获取,因为getChildAt对应的index不一定 为vp中child实际的排列顺序(左右拖动时,打log即可验证)。此时可根据各child的x值重新排序,再用vp.getChildAt即可。

public static View getCurChild_vp(ViewPager vp) {

		int childCnt = vp.getChildCount();
		int totalCnt = vp.getAdapter().getCount();
		int curItem = vp.getCurrentItem();

		int targetIndex = 0;

		// 若"已加载child未达到应有值",则在边界 、或总数达不到limit
		if (childCnt < vp.getOffscreenPageLimit() * 2 + 1) {
			// 若-项数不足-加载所有至limit,直接返回当前
			if (childCnt == totalCnt)
				targetIndex = curItem;
			else
			// 若足
			{
				// 若在左边界(即左边child数未达到limit)
				if (curItem - vp.getOffscreenPageLimit() < 0)
					targetIndex = curItem;
				// 右边界
				else
					targetIndex = vp.getOffscreenPageLimit();
			}
		}
		// childCnt完整(即总项>childCnt,且不在边界)
		else
			targetIndex = vp.getOffscreenPageLimit();

		// 取-子元素
		List<View> vs = new ArrayList<View>();
		for (int i = 0; i < childCnt; i++)
			vs.add(vp.getChildAt(i));

		// 对子元素-排序,因默认排序-不一定正确(viewpager内部机制)
		Collections.sort(vs, new Comparator<View>() {
			@Override
			public int compare(View lhs, View rhs) {
				// TODO Auto-generated method stub
				if (lhs.getLeft() > rhs.getLeft())
					return 1;
				else if (lhs.getLeft() < rhs.getLeft())
					return -1;
				else
					return 0;
			}
		});

		// debug
		// for (int i = 0; i<childCnt; i++)
		// System.out.println("nimei>>vp-"+i+".x:"+vs.get(i).getLeft());
		// System.out.println("nimei>>index:"+targetIndex);

		return vs.get(targetIndex);
	}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/163222.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号