[英]4 layouts 1 page in a ViewPager
I have a ViewPager with which I want 4 instances of a layout displayed on the screen at a time, and you scroll to look at the next 4. This means I either need to add 4 instances of the layout to a single page, or I need to tell the ViewPager to scroll 4 pages at a time. 我有一个ViewPager,我想一次在屏幕上显示4个版式实例,然后滚动查看下一个4。这意味着我要么需要在单个页面上添加4个版式实例,要么需要告诉ViewPager一次滚动4页。 I'd like to do this without making 4 copies of a layout in the same xml. 我想做到的是在同一xml中不制作布局的4个副本。 Here's how I'm handling this now: 这是我现在处理的方式:
@Override
public Object instantiateItem(ViewGroup container, int position)
{
LinearLayout toReturn = new LinearLayout(getActivity());
toReturn.setOrientation(LinearLayout.HORIZONTAL);
for(int i = position; i < position + 4; i++)
{
View layout = getActivity().getLayoutInflater().inflate(R.layout.viewpager_fragment_layout, container, false);
toReturn.addView(layout);
}
container.addView(toReturn);
return toReturn;
}
The result is the same as though I were adding each layout to the ViewPager 1 at a time instead of grouping them up into a single layout. 结果就像是一次将每个布局添加到ViewPager 1一样,而不是将它们分组为一个单独的布局。 It displays 4 layouts on the screen at a time, but when you scroll, you only move past 1 layout at a time. 它一次在屏幕上显示4个布局,但是滚动时,一次只能移动1个布局。
Override getPageWidth()
in your PagerAdapter
to return the portion of the screen to use for a page. 在您的PagerAdapter
重写getPageWidth()
以返回用于页面的屏幕部分。 For four pages at a time, returning 0.25
should work. 对于一次四页,返回0.25
应该可以。
Here is a sample project demonstrating this. 这是一个演示此的示例项目 。 Also here is a blog post outlining this technique and a couple of others. 另外, 这里是一篇博客文章,概述了该技术以及其他一些技术。
With regards to your current code, I do not know for certain how you are determining that "when you scroll, you only move past 1 layout at a time". 关于您当前的代码,我不确定您如何确定“滚动时一次只能移动1个布局”。 After all, since you are not changing anything in the layouts, they all look the same. 毕竟,由于您没有更改布局中的任何内容,因此它们看起来都是一样的。
Hence, I am going to make two assumptions, that would seem to fit your described symptoms: 因此,我将做出两个假设,这些假设似乎符合您描述的症状:
There is code that you elected not to show between your inflate()
call and your addView()
call. 还有就是你选择将您之间显示的代码inflate()
调用,您addView()
调用。
The code in question is populating the widgets based on position
. 有问题的代码是根据position
填充小部件的。
Bear in mind that position
is the page index , not the layout index . 请记住, position
是页面索引 ,而不是布局索引 。
Let's suppose that you have 12 total layouts. 假设您总共有12个布局。 You want to show those in 3 pages in a ViewPager
. 您想在ViewPager
3页中显示它们。 Hence, getPageCount()
should be returning 3. And instead of: 因此, getPageCount()
应该返回3。而不是:
for(int i = position; i < position + 4; i++) {
I would expect to see: 我希望看到:
for(int layout_offset = 0; layout_offset < 4; layout_offset++) {
int i=(position*4)+layout_offset;
(though I would have named i
to be layout_index
or something) (虽然我会叫i
是layout_index
或东西)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.