ViewPager不能高度自适应?height=wrap_content 无效解决办法

来源:互联网 发布:mac air 能换 编辑:程序博客网 时间:2024/05/12 03:00

ViewPager用的很多,主要用啦展示广告条。可是高度却不能自适应内容,总是会占满全屏,即使设置android:height="wrap_content"也是没有用的。。

解决办法其实网上有很多,但是个人感觉不是很好

比如:LinearLayout的时候,使用weight来自动调整ViewPager的高度。

一般的代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <android.support.v4.view.ViewPager        android:id="@+id/pager"        android:layout_width="fill_parent"        android:layout_height="0dp"        android:layout_weight="1.0" />    <ImageView        android:id="@+id/ivCursor"        android:layout_width="60dp"        android:layout_height="5dp"        android:scaleType="fitCenter"        android:src="@drawable/cursor" />    <LinearLayout        android:id="@+id/tabs"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>

这段代码中,就用了weight来保证ViewPager始终占满屏幕的剩余空间。如果ViewPager里面的内容不需要那么高,怎么办?这个方法就不行了。

还比如:固定ViewPager的高度。height="100dp"。

这样也不是很好。当服务器为了保证图片在不同dpi的手机上,不被缩放,返回的图片高度也有可能不同,固定高度就造成了不能很好的适应这钟变化。

在实际开发中,本人用的最多的就是通过LayoutParmas动态改变ViewPager的高度。

个人感觉这个方法不错还比较简单。

在给ViewPager设置View的时候,通过获取view的高度,动态的设置ViewPager的高度等于view的高度,就OK了。

int viewPagerIndex = main.indexOf(viewPager);int childViewHeight = getChildViewHeight(); //获取ViewPager的子View的高度。LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, childViewHeight );//这里设置params的高度。main.removeView(viewPager);main.addView(viewPager, viewPagerIndex , params);//使用这个params


或者,直接继承ViewPager,在onMeasure中返回childView的高度。

这样布局的时候,就会使用childView的高度了。思路和上面一样。代码如下:

import android.content.Context;import android.support.v4.view.ViewPager;import android.util.AttributeSet;import android.view.View;public class WrapContentHeightViewPager extends ViewPager {public WrapContentHeightViewPager(Context context) {super(context);}public WrapContentHeightViewPager(Context context, AttributeSet attrs) {super(context, attrs);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int height = 0;//下面遍历所有child的高度for (int i = 0; i < getChildCount(); i++) {View child = getChildAt(i);child.measure(widthMeasureSpec,MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));int h = child.getMeasuredHeight();if (h > height) //采用最大的view的高度。height = h;}heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);super.onMeasure(widthMeasureSpec, heightMeasureSpec);}}

0 0
原创粉丝点击