【问题标题】:how do I add margin at the end of a ViewPager?如何在 ViewPager 的末尾添加边距?
【发布时间】:2017-11-30 16:33:55
【问题描述】:

我正在处理使用 viewpager 在片段中显示图像水平列表(而不是 listview 或 recyclerview)的遗留代码。 viewpager 使用自定义 PagerAdapter 覆盖适当的方法(instantiateItem、getItemPositiion 等)。我现在的问题是我想在 viewpager 的最后一个元素的末尾添加一些空间,我试图通过在这个最后一个元素上添加一个边距来做到这一点。

public Object instantiateItem(ViewGroup collection, int position) {
    FrameLayout itemView = ViewManager.createView(position, height, type);
    int viewWidth = itemView.getLayoutParams().width;
    RelativeLayout itemViewWrap = new RelativeLayout(mContext);
    if(postion == items.size()-1){
        RelativeLayout.LayoutParams itemViewparams = RelaiveLayout.LayoutParams)itemView.getLayoutParams();
        itemViewparams.setMargins(0, 0, viewWidth, 0);
    }
    itemViewWrap.addView(itemView);
    collection.addView(itemViewWrap);
    return itemView;
}

不幸的是,这不起作用,最终元素没有显示。我该如何正确实现这一目标?这是该 viewpager 所在片段的 xml。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.playground.test.views.ItemViewPager
        android:id="@+id/viewpager"
        android:layout_gravity="center_vertical"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>

</RelativeLayout>

【问题讨论】:

  • 您可以尝试添加一个新的“最后一项”作为空白视图,其中包含您想要的边距/填充空间
  • 您将边距设置为视图右侧,边距等于视图,这就是项目视图不可见的原因。尝试 itemViewparams.setMargins(0, 0, viewWidth/2, 0);而不是 itemViewparams.setMargins(0, 0, viewWidth, 0);
  • @motis10 试图避免这样做,因为 viewpager 应该只包含有效元素并与支持数组一一匹配。
  • @NirmalPrajapat 这样做会切断最后一个 viewpager 元素的一半,而不是在末尾添加边距。
  • @Oyebisi ,哦,然后尝试填充而不是边距。

标签: android android-layout android-viewpager


【解决方案1】:

您可以使用 ViewPagerAdapter# getPageWidth 覆盖最后一页的宽度。比页面的其余部分多出你想要的页边距。

https://developer.android.com/reference/android/support/v4/view/PagerAdapter.html#getPageWidth(int)

【讨论】:

    猜你喜欢
    • 2017-06-15
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多