在viewpager当中直接使用layout_width="wrap_content"是无效的,扩展了一下。解决这个问题。
看下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | package com.soulagou.ui; import android.content.Context; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; /** * * @author pangxg * @title 扩展viewPager * @description 和一般的ViewPager一样使用 */ public class ViewPager extends android.support.v4.view.ViewPager{ //private static final String tag=ViewPager.class.getSimpleName(); protected ViewPager viewPager=null; protected final int wrap_content=-2; protected final int match_parent=-1; protected int w =match_parent; protected int h =match_parent; protected int ph =match_parent; protected int pw =match_parent; public ViewPager(Context context) { super(context); viewPager=this; } public ViewPager(Context context, AttributeSet attrs) { super(context, attrs); viewPager=this; } @Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { super.onLayout(arg0, arg1, arg2, arg3, arg4); ViewGroup.LayoutParams params =null; ph=viewPager.getLayoutParams().height; pw=viewPager.getLayoutParams().width; Drawable bg= viewPager.getBackground(); if (bg!=null) { int h = bg.getIntrinsicHeight(); int w= bg.getIntrinsicWidth(); if (ph==wrap_content) { this.h=h; }else if( ph==match_parent) { this.h=ph; } if (pw==wrap_content) { this.w=w; }else if( pw==match_parent) { this.w=pw; } } viewPager.setBackgroundColor(getResources().getColor(android.R.color.transparent)); ViewParent pv=viewPager.getParent(); if (pv instanceof LinearLayout) { params = new LinearLayout.LayoutParams(this.w, this.h); }else if (pv instanceof RelativeLayout) { params = new RelativeLayout.LayoutParams(this.w, this.h); }else if (pv instanceof FrameLayout) { params = new FrameLayout.LayoutParams(this.w, this.h); } viewPager.setLayoutParams(params); } @Override protected void onMeasure(int arg0, int arg1) { super.onMeasure(arg0, arg1); } } |
在xml中和原来的viewPager一样使用就可以了。
1 2 3 4 5 6 7 8 9 10 | <FrameLayout android:layout_marginTop="13dp" android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bord_indexbg"> <com.soulagou.ui.ViewPager android:id="@+id/myindex_guidePager" android:layout_gravity="center_horizontal" android:layout_marginTop="5dp" android:background="@drawable/defa_advpic" android:layout_width="wrap_content" android:layout_height="wrap_content"> </com.soulagou.ui.ViewPager> </FrameLayout> |
好用吧。