ViewPager不能高度自適應?height=wrap_content 無效解決辦法


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);
  }

  @Override
  protected 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);
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM