Android:ViewPager WRAP_CONTENTを使用できません


258

各ページに200dpの高さのImageViewを持つ単純なViewPagerをセットアップしました。

これが私のポケットベルです:

pager = new ViewPager(this);
pager.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
pager.setBackgroundColor(Color.WHITE);
pager.setOnPageChangeListener(listener);
layout.addView(pager);

高さがwrap_contentに設定されているにもかかわらず、イメージビューが200 dpしかない場合でも、ページャーは常に画面いっぱいに表示されます。ページャーの高さを「200」に置き換えようとしましたが、複数の解像度で異なる結果が得られました。その値に「dp」を追加できません。ページャーのレイアウトに200dpを追加するにはどうすればよいですか?


1
してくださいスター発行code.google.com/p/android/issues/detail?id=54604
キリスト

回答:


408

ViewPager次のようにonMeasureをオーバーライドすると、現在の最大の子の高さが取得されます。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int height = 0;
    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) height = h;
    }

    if (height != 0) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

24
これは私が必要なものに最も近いが、追加するには、2つのものがあります: 1.ザ・ViewPagerがあるだけで、実際の子供、唯一の現在に表示されるアイテムと直接隣接するものの最大にサイズ変更します。ViewPagerでsetOffscreenPageLimit(子の総数)を呼び出すと、これが解決され、サイズがすべての項目の最大に設定され、サイズ変更されないViewPagerが生成されます。 2. WebViewを測定しようとすると、奇妙な問題がいくつかあります。何かをロードした後にWebViewでrequestLayout()を呼び出すと、それが解決します。
0101100101 2014

3
私が修正する小さな問題があります。viewPagerの可視性がGONEであり、それを可視に設定した場合、フラグメントが作成される前にonMeasureが呼び出されます。つまり、高さは0になります。アイデアがあれば、彼を歓迎します。フラグメントが作成されたときのためのコールバックを使用すると思います
edoardotognoni 2014年

4
これは、装飾の子ビューがある場合は機能しません-これは、ViewPager.onMeasure()が装飾ビューを測定して最初にそれらにスペースを割り当て、次に残りのスペースを非装飾の子に与えるためです。それにもかかわらず、これはこれまでで最も不正確な解決策なので、私は賛成票を投じました;)
ベンジャミン・ドベル

3
私はViewPagerを使用するたびにこれに戻ってきます
小野

7
getChildCount()は、ViewPagerでsetAdapter()をすでに実行しているときに0を返す場合があります。(ビューを作成する)実際のpopulate()呼び出しは、super.onMeasure(widthMeasureSpec、heightMeasureSpec);の内部で行われます。コール。この関数の先頭に余分なsuper.onMeasure()呼び出しを置くとうまくいきました。また、stackoverflow.com
questions / 38492210 /…を

106

別のより一般的な解決策は、 wrap_content仕事だけことです。

ViewPagerオーバーライドするように拡張しましたonMeasure()。高さは最初の子ビューの周りにラップされます。これにより、子ビューの高さがまったく同じでない場合、予期しない結果が生じる可能性があります。そのため、クラスを簡単に拡張して、現在のビュー/ページのサイズにアニメーション化するとしましょう。しかし、私はそれを必要としませんでした。

元のViewPagerと同じように、このViewPagerをXMLレイアウトで使用できます。

<view
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    class="de.cybergen.ui.layout.WrapContentHeightViewPager"
    android:id="@+id/wrapContentHeightViewPager"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"/>

利点:このアプローチでは、RelativeLayoutを含む任意のレイアウトでViewPagerを使用して、他のUI要素をオーバーレイできます。

欠点が1つ残っています。マージンを使用したい場合は、2つのネストされたレイアウトを作成し、内側のレイアウトに必要なマージンを与える必要があります。

これがコードです:

public class WrapContentHeightViewPager extends ViewPager {

    /**
     * Constructor
     *
     * @param context the context
     */
    public WrapContentHeightViewPager(Context context) {
        super(context);
    }

    /**
     * Constructor
     *
     * @param context the context
     * @param attrs the attribute set
     */
    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // find the first child view
        View view = getChildAt(0);
        if (view != null) {
            // measure the first child view with the specified measure spec
            view.measure(widthMeasureSpec, heightMeasureSpec);
        }

        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
    }

    /**
     * Determines the height of this view
     *
     * @param measureSpec A measureSpec packed into an int
     * @param view the base view with already measured height
     *
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec, View view) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            // set the height from the base view if available
            if (view != null) {
                result = view.getMeasuredHeight();
            }
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

}

34
ビューページャーが破棄されて再び開かれたときに、他の誰かが現在のアイテムの横に空白ページを取得しましたか?
Zyoo 2014年

1
白紙も取れました。
aeren 2014

10
私のブログで説明されているように、この質問の2つの上位回答をマージする必要があるだけです。pristalovpavel.wordpress.com
anil

4
'onMeasure'メソッドのコードを 'DanielLópezLacalle'によって与えられた答えに置き換えるだけです。
Yog Guru

1
すごい..!私のために働いた.. @cybergenありがとう、あなたは私の一日を救った..!
Dnyanesh M 2017

59

私は、ダニエルロペスラカーレとこの投稿http://www.henning.ms/2013/09/09/viewpager-that-simply-dont-measure-up/に基づいて私の回答を作成しました。ダニエルの答えの問題は、私の子供たちの高さがゼロの場合があることです。解決策は、残念ながら2回測定することでした。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mode = MeasureSpec.getMode(heightMeasureSpec);
    // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
    // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
    if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
        // super has to be called in the beginning so the child views can be initialized.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        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) height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }
    // super has to be called again so the new specs are treated as exact measurements
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

これにより、必要に応じて、または単にwrap_contentを使用する場合に、ViewPagerに高さを設定することもできます。


私は同じ問題を抱えていて、あなたの答えでそれを解決しました、ありがとう。しかし、理由に関する説明はありますか?
Bart Burg

彼らがラップコンテンツをサポートするつもりはなかったと思います。通常の使用例だとは思わなかったからです。それをサポートするには、コンテンツをラップできるように、子供が測定された後で自分自身を再測定する必要があります。
MinceMan 2016

なぜ、このViewPagerの画像は、同じ使用ImageViewのに比べactualy短いscaleType、同様とするlayout_width=match_parentだけでなく、layout_height=wrap_content?20dpが足りないようです。
Shark

サメ、本当にわかりません。これは、スケールタイプが実際に行っていることと関係がある可能性があります。高さを設定してみてください。
MinceMan、2016年

1
私はそれを信じることはできません!カスタムビューページャーを接着するのに2日間費やしましたが、最初のビューが表示されず、理由がわからなかったときに問題が発生しました。// super has to be called in the beginning so the child views can be initialized.<-----それが理由で、onMeasure関数の開始時と終了時にそれを呼び出さなければなりませんでした。Yippiii、今日のバーチャルハイファイブ!
Starwave、

37

私はこれについて非常によく似た質問に答えていたところ、私の申し立てをバックアップするためのリンクを探しているときにたまたまこれを見つけたので、幸運です:)

私の他の答え:
ViewPagerはwrap_content、(通常)すべての子が同時に読み込まれることはないためサポートしません。したがって、適切なサイズを取得できません(オプションは、ページャーを切り替えるたびにサイズを変更することです)ページ)。

ただし、正確なサイズ(150dpなど)を設定することもできmatch_parentます。
height-attributeを変更することで、コードから動的に次元を変更することもできますLayoutParams

ニーズに応じて、viewPagerを独自のxmlファイルで作成し、layout_heightを200dpに設定してから、コードで新しいViewPagerを最初から作成するのではなく、そのxmlファイルをインフレートできます。

LayoutInflater inflater = context.getLayoutInflater();
inflater.inflate(R.layout.viewpagerxml, layout, true);

3
デフォルトの動作が「やや理解できないことをする」ことは不愉快なことです。説明ありがとう。
Chris Vandevelde 2012年

8
@ChrisVandeveldeこれは、いくつかのAndroidライブラリの一般的なテナントのようです。基本を学ぶとすぐに、何もそれらに追随しないことに気付きます
CQM

1
しかし、@ Jave、なぜビューページャはその子がロードされるたびに高さを調整できないのですか?
Diffy 2014

@CQM確かに!ViewPagerIndicatorライブラリもにlayout_height設定すると同じ問題が発生しますがwrap_content、固定量に設定するという単純な回避策が機能しないため、さらに問題があります。
Giulio Piancastelli 2014

20

DanielLópezLocalleの回答を使用して、このクラスをKotlinで作成しました。もっと時間を節約してほしい

class DynamicHeightViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ViewPager(context, attrs) {

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    var heightMeasureSpec = heightMeasureSpec

    var height = 0
    for (i in 0 until childCount) {
        val child = getChildAt(i)
        child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
        val h = child.measuredHeight
        if (h > height) height = h
    }

    if (height != 0) {
        heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}}

16

私はすでにいくつかのプロジェクトでこの問題に直面しており、完全な解決策はありませんでした。そこで、ViewPagerのインプレース置換としてWrapContentViewPager githubプロジェクトを作成しました。

https://github.com/rnevet/WCViewPager

ソリューションは、ここでの回答のいくつかに触発されましたが、次の点で改善されています。

  • スクロール中も含め、現在のビューに応じて動的にViewPagerの高さを変更します。
  • PagerTabStripのような「装飾」ビューの高さを考慮に入れます。
  • すべてのパディングを考慮に入れます。

以前の実装に違反していたサポートライブラリバージョン24用に更新されました。


@mvaiで問題を開いたり、フォークしてサンプルアプリを変更したりできますか?
Raanan

1
RecyclerViewにもwrap_contentの問題があることがわかりました。このようにカスタムのLinearLayoutManagerを使用すると機能します。ライブラリに問題はありません。
natario 2015

1
まだ修正が必要なのは、FragmentStatePagerAdapterでの使用です。フラグメントが配置される前に子を測定しているため、高さが低くなっています。私のために働いていたのは@loganの答えでしたが、私はまだそれに取り組んでいます。そのアプローチをライブラリにマージしてみてください。申し訳ありませんが、githubに詳しくありません。
natario 2015

よろしくお願いします。
Raanan

1
FragmentPagerAdapterでこれを機能させる方法を知りたい場合は、getObjectAtPositionメソッドから対応するFragmentを返すことができるように、フラグメントのリストを内部的に保持して、アダプターにObjectAtPositionInterfaceを実装させます。
Pablo

15

私はちょうど同じ問題にぶつかった。私はViewPagerを持っていて、そのボタンに広告を表示したいと思っていました。私が見つけた解決策は、ページャーをRelativeViewに入れ、そのlayout_aboveをその下に表示したいビューIDに設定することでした。それは私のために働いた。

ここに私のレイアウトXMLがあります:

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

    <LinearLayout
        android:id="@+id/AdLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/mainpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/AdLayout" >
    </android.support.v4.view.ViewPager>
</RelativeLayout>

4
参考までに、両方にxmlns:android = " schemas.android.com/apk/res/android " は必要ありません。最初の1つだけです
Martin Marconcini、2013

2
あなたの問題はまったく同じではありませんでした。ViewPagerをmatch_parentに設定すると、レイアウトは正常に機能します。OPは、ViewPagerをコンテンツにラップする必要があるという状況にありました。
k2col 2016年

9

私もこの問題に遭遇しましたが、私の場合、ページFragmentPagerAdapterをに提供するViewPagerがありました。私が抱えていた問題onMeasure()は、ViewPagerFragments作成される前にが呼び出されたことでした(そのため、サイズを正しく設定できませんでした)。

試行錯誤のビットの後、私はことを発見しfinishUpdate()た後FragmentPagerAdapterのメソッドが呼び出されるFragments(から初期化されているinstantiateItem()中でFragmentPagerAdapter)、また、後/ページスクロール中。私は小さなインターフェースを作りました:

public interface AdapterFinishUpdateCallbacks
{
    void onFinishUpdate();
}

これを自分に渡してFragmentPagerAdapter呼び出す:

@Override
public void finishUpdate(ViewGroup container)
{
    super.finishUpdate(container);

    if (this.listener != null)
    {
        this.listener.onFinishUpdate();
    }
}

これによりsetVariableHeight()CustomViewPager実装を呼び出すことができます。

public void setVariableHeight()
{
    // super.measure() calls finishUpdate() in adapter, so need this to stop infinite loop
    if (!this.isSettingHeight)
    {
        this.isSettingHeight = true;

        int maxChildHeight = 0;
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
        for (int i = 0; i < getChildCount(); i++)
        {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED));
            maxChildHeight = child.getMeasuredHeight() > maxChildHeight ? child.getMeasuredHeight() : maxChildHeight;
        }

        int height = maxChildHeight + getPaddingTop() + getPaddingBottom();
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

        super.measure(widthMeasureSpec, heightMeasureSpec);
        requestLayout();

        this.isSettingHeight = false;
    }
}

私はそれが最良のアプローチであるかどうかはわかりませんが、それが良い/悪い/悪いと思うならコメントが大好きですが、私の実装ではかなりうまく機能しているようです:)

これが誰かに役立つことを願っています!

編集:私はrequestLayout()呼び出し後にアフターを追加するのを忘れましたsuper.measure()(そうでなければ、それはビューを再描画しません)。

また、親のパディングを最終的な高さに追加するのを忘れていました。

また、必要に応じて新しいものを作成するために、元の幅/高さのMeasureSpecsを維持することもやめました。それに応じてコードを更新しました。

私が持っていた別の問題は、それ自体がa ScrollViewで正しくサイズ調整されないことであり、犯人がのMeasureSpec.EXACTLY代わりにで子供を測定していることがわかりましたMeasureSpec.UNSPECIFIED。これを反映するように更新されました。

これらの変更はすべてコードに追加されています。必要に応じて、履歴を確認して古い(正しくない)バージョンを確認できます。


コードに忘れたものを追加しないでください。
ハサン、2014年

@ハサン私はすでにやった、混乱してすみません!同じことを言うために答えを更新します
ローガン2014年

驚くばかり!それが役に立ててうれしい:)
ローガン14

8

別の解決策はViewPager、の現在のページの高さに従って高さを更新することPagerAdapterです。あなたがViewPagerこの方法であなたのページを作成していると仮定します:

@Override
public Object instantiateItem(ViewGroup container, int position) {
  PageInfo item = mPages.get(position);
  item.mImageView = new CustomImageView(container.getContext());
  item.mImageView.setImageDrawable(item.mDrawable);
  container.addView(item.mImageView, 0);
  return item;
}

ここでmPagesの内部リストされているPageInfo構造を動的に追加PagerAdapterし、CustomImageView普通のあるImageViewオーバーライドとonMeasure()指定された幅に応じてその高さを設定し、画像の縦横比を維持する方法。

メソッドでViewPager高さを強制できますsetPrimaryItem()

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
  super.setPrimaryItem(container, position, object);

  PageInfo item = (PageInfo) object;
  ViewPager pager = (ViewPager) container;
  int width = item.mImageView.getMeasuredWidth();
  int height = item.mImageView.getMeasuredHeight();
  pager.setLayoutParams(new FrameLayout.LayoutParams(width, Math.max(height, 1)));
}

に注意してくださいMath.max(height, 1)。これViewPagerにより、表示されたページが更新されない(空白で表示される)迷惑なバグが修正されます。前のページの高さがゼロ(つまり、でnull描画可能CustomImageView)の場合、2つのページ間を奇妙にスワイプします。


私には正しい道をたどっているようですがitem.mImageView.measure(..)getMeasuredXXX()メソッドで正しい寸法を取得するにはa を広告する必要がありました。
Gianluca P. 14

6

ビューページャー内で静的コンテンツを使用していて、派手なアニメーションを望まない場合は、次のビューページャーを使用できます。

public class HeightWrappingViewPager extends ViewPager {

  public HeightWrappingViewPager(Context context) {
    super(context);
  }

  public HeightWrappingViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)   {
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);
      View firstChild = getChildAt(0);
      firstChild.measure(widthMeasureSpec, heightMeasureSpec);
      super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(firstChild.getMeasuredHeight(), MeasureSpec.EXACTLY));
  }
}

これは正常に動作します。私は子供たちをループして最大の高さの子供を連れてそれを拡張しました。
JavierMendonça16年

リサイクラーのビューの下でも問題なく動作する
kanudo 2017

この例外が発生します
-java.lang.NullPointerException:

しかし、最初の要素を取ることは間違っているかもしれません。
トビアスライヒ

4
public CustomPager (Context context) {
    super(context);
}

public CustomPager (Context context, AttributeSet attrs) {
    super(context, attrs);
}

int getMeasureExactly(View child, int widthMeasureSpec) {
    child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    int height = child.getMeasuredHeight();
    return MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;

    final View tab = getChildAt(0);
    if (tab == null) {
        return;
    }

    int width = getMeasuredWidth();
    if (wrapHeight) {
        // Keep the current measured width.
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
    }
    Fragment fragment = ((Fragment) getAdapter().instantiateItem(this, getCurrentItem()));
    heightMeasureSpec = getMeasureExactly(fragment.getView(), widthMeasureSpec);

    //Log.i(Constants.TAG, "item :" + getCurrentItem() + "|height" + heightMeasureSpec);
    // super has to be called again so the new specs are treated as
    // exact measurements.
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

4

ポップコーンの時代のandroidアプリのソースコードから、現在の子のサイズに応じて素敵なアニメーションでビューページャーのサイズを動的に調整するこのソリューションを見つけました。

https://git.popcorntime.io/popcorntime/android/blob/5934f8d0c8fed39af213af4512272d12d2efb6a6/mobile/src/main/java/pct/droid/widget/WrappingViewPager.java

public class WrappingViewPager extends ViewPager {

    private Boolean mAnimStarted = false;

    public WrappingViewPager(Context context) {
        super(context);
    }

    public WrappingViewPager(Context context, AttributeSet attrs){
        super(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if(!mAnimStarted && null != getAdapter()) {
            int height = 0;
            View child = ((FragmentPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
            if (child != null) {
                child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                height = child.getMeasuredHeight();
                if (VersionUtils.isJellyBean() && height < getMinimumHeight()) {
                    height = getMinimumHeight();
                }
            }

            // Not the best place to put this animation, but it works pretty good.
            int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
                    final int targetHeight = height;
                    final int currentHeight = getLayoutParams().height;
                    final int heightChange = targetHeight - currentHeight;

                    Animation a = new Animation() {
                        @Override
                        protected void applyTransformation(float interpolatedTime, Transformation t) {
                            if (interpolatedTime >= 1) {
                                getLayoutParams().height = targetHeight;
                            } else {
                                int stepHeight = (int) (heightChange * interpolatedTime);
                                getLayoutParams().height = currentHeight + stepHeight;
                            }
                            requestLayout();
                        }

                        @Override
                        public boolean willChangeBounds() {
                            return true;
                        }
                    };

                    a.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                            mAnimStarted = true;
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            mAnimStarted = false;
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });

                    a.setDuration(1000);
                    startAnimation(a);
                    mAnimStarted = true;
            } else {
                heightMeasureSpec = newHeight;
            }
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

4

サイズを最大のだけでなくすべての子に合わせ調整するViewPagerが必要な場合に備えて、それを行うコードを書きました。その変更時にアニメーションがないことに注意してください(私の場合は必要ありません)

android:minHeightフラグもサポートされています。

public class ChildWrappingAdjustableViewPager extends ViewPager {
    List<Integer> childHeights = new ArrayList<>(getChildCount());
    int minHeight = 0;
    int currentPos = 0;

    public ChildWrappingAdjustableViewPager(@NonNull Context context) {
        super(context);
        setOnPageChangeListener();
    }

    public ChildWrappingAdjustableViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        obtainMinHeightAttribute(context, attrs);
        setOnPageChangeListener();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {            
        childHeights.clear();

        //calculate child views
        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 < minHeight) {
                h = minHeight;
            }
            childHeights.add(i, h);
        }

        if (childHeights.size() - 1 >= currentPos) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeights.get(currentPos), MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private void obtainMinHeightAttribute(@NonNull Context context, @Nullable AttributeSet attrs) {
        int[] heightAttr = new int[]{android.R.attr.minHeight};
        TypedArray typedArray = context.obtainStyledAttributes(attrs, heightAttr);
        minHeight = typedArray.getDimensionPixelOffset(0, -666);
        typedArray.recycle();
    }

    private void setOnPageChangeListener() {
        this.addOnPageChangeListener(new SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                currentPos = position;

                ViewGroup.LayoutParams layoutParams = ChildWrappingAdjustableViewPager.this.getLayoutParams();
                layoutParams.height = childHeights.get(position);
                ChildWrappingAdjustableViewPager.this.setLayoutParams(layoutParams);
                ChildWrappingAdjustableViewPager.this.invalidate();
            }
        });
    }
}

したがって、このアダプターには、アダプター内のアイテムの量が変更されると大きな問題があります
jobbert

あなたの声明を明確にできますか?
Phatee P

すべての子が最初に計算されるわけではないので、このコードはnullpointersを引き起こす可能性があります。タブレイアウトを試し、1から5までスクロールするか、コードを賢くスクロールすると、表示されます。
jobbert

4

DanielLópezLacalleの回答を改善し、Kotlinで書き直しました:

class MyViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val zeroHeight = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)

        val maxHeight = children
            .map { it.measure(widthMeasureSpec, zeroHeight); it.measuredHeight }
            .max() ?: 0

        if (maxHeight > 0) {
            val maxHeightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY)
            super.onMeasure(widthMeasureSpec, maxHeightSpec)
            return
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }
}

3

私は同じ問題にぶつかり、ユーザーがページ間をスクロールしたときにViewPagerがそのコンテンツを折り返すようにする必要もありました。cybergenの上記の回答を使用して、onMeasureメソッドを次のように定義しました。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    if (getCurrentItem() < getChildCount()) {
        View child = getChildAt(getCurrentItem());
        if (child.getVisibility() != GONE) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec),
                    MeasureSpec.UNSPECIFIED);
            child.measure(widthMeasureSpec, heightMeasureSpec);
        }

        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, getChildAt(getCurrentItem())));            
    }
}

このように、onMeasureメソッドは、ViewPagerによって表示される現在のページの高さを設定します。


最も高さの高いコンテンツのみが回答とともに表示され、他のコンテンツは表示されなくなります...
Blaze Tama

2

上記の提案のどれも私にとってはうまくいきませんでした。私の使用例では、4つのカスタムViewPagersを使用していScrollViewます。それらのトップはアスペクト比に基づいて測定され、残りはちょうど持っていlayout_height=wrap_contentます。私はcybergenDanielLópezLacalleソリューションを試しました。それらのどれも私のために完全に機能しません。

cybergenが1ページ> 1で機能しない理由は、ページ1に基づいてページャーの高さを計算するためだと思います。さらにスクロールすると非表示になります。

cybergenDanielLópezLacalleの提案はどちらも私の場合奇妙な動作をします。3つのうち 2つは正常に読み込まれ、1つはランダムに高さが0 onMeasureです。子が入力される前に呼び出されたように見えます。だから私はこれらの2つの答えと私自身の修正の組み合わせを思いつきました:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
        // find the first child view
        View view = getChildAt(0);
        if (view != null) {
            // measure the first child view with the specified measure spec
            view.measure(widthMeasureSpec, heightMeasureSpec);
            int h = view.getMeasuredHeight();
            setMeasuredDimension(getMeasuredWidth(), h);
            //do not recalculate height anymore
            getLayoutParams().height = h;
        }
    }
}

アイデアは、ViewPager子供の寸法を計算させ、最初のページの計算された高さをのレイアウトパラメータに保存することViewPagerです。フラグメントのレイアウトの高さを設定することを忘れないでくださいwrap_content。そうしないと、height = 0を取得できます。私はこれを使いました:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="wrap_content">
        <!-- Childs are populated in fragment -->
</LinearLayout>

このソリューションは、すべてのページの高さが同じである場合に適切に機能することに注意してください。それ以外の場合はViewPager、現在アクティブな子に基づいて高さを再計算する必要があります。私はそれは必要ありませんが、あなたが解決策を提案した場合、私は答えを更新させていただきます。


これらの年をすべて過ぎても、回答を更新できますか?私を1トン助けてくれる
デニー

2

この問題があり、Xamarin AndroidをC#でコーディングしている人にとっては、これも簡単な解決策になる可能性があります。

pager.ChildViewAdded += (sender, e) => {
    e.Child.Measure ((int)MeasureSpecMode.Unspecified, (int)MeasureSpecMode.Unspecified);
    e.Parent.LayoutParameters.Height = e.Child.MeasuredHeight;
};

これは主に、子ビューの高さが同じ場合に役立ちます。それ以外の場合は、チェックするすべての子に対して何らかの「minimumHeight」値を格納する必要があり、それでも小さな子ビューの下に空のスペースを表示したくない場合があります。

ソリューション自体は私にとっては十分ではありませんが、それは私の子アイテムがlistViewsであり、それらのMeasuredHeightが正しく計算されていないためです。


これでうまくいきました。ビューページャーのすべての子ビューは同じ高さです。
ドミトリー

2

選択した現在の子ビューに基づいて親ビューの高さのベースをサイズ変更するAPI 23より前のバージョンで正常に動作していたWrapContentHeightViewPagerのバージョンがあります。

API 23にアップグレードした後、機能しなくなりました。getChildAt(getCurrentItem())現在の子ビューを測定するために使用していた古いソリューションが機能していないことがわかりました。ここでソリューションを参照してください:https : //stackoverflow.com/a/16512217/1265583

以下はAPI 23で動作します:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = 0;
    ViewPagerAdapter adapter = (ViewPagerAdapter)getAdapter();
    View child = adapter.getItem(getCurrentItem()).getView();
    if(child != null) {
        child.measure(widthMeasureSpec,  MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        height = child.getMeasuredHeight();
    }
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

ありがとうございました!!何時間も答えを試みてきましたが、これが私にとって完全に機能する唯一のものです。これは、「setPrimaryItem()」がページャーの関数を呼び出すカスタムアダプターと組み合わせる必要があるrequestLayout()ため、タブ間を移動するときに高さが調整されます。なぜsuper2回呼び出す必要があるのか覚えていますか?それ以外の場合は機能しないことに気づきました。
M3RS 2018

API 28で動作します
ハリドLakhani

2

以下のコードは私のために働いた唯一のものです

1.このクラスを使用して、HeightWrappingViewPagerを宣言します。

 public class HeightWrappingViewPager extends ViewPager {

        public HeightWrappingViewPager(Context context) {
            super(context);
        }

        public HeightWrappingViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int mode = MeasureSpec.getMode(heightMeasureSpec);
            // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
            // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
            if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
                // super has to be called in the beginning so the child views can be initialized.
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                int height = 0;
                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) height = h;
                }
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            }
            // super has to be called again so the new specs are treated as exact measurements
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

2.高さラッピングビューページャーをxmlファイルに挿入します。

<com.project.test.HeightWrappingViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</com.project.test.HeightWrappingViewPager>

3.ビューページャーを宣言します。

HeightWrappingViewPager mViewPager;
mViewPager = (HeightWrappingViewPager) itemView.findViewById(R.id.pager);
CustomAdapter adapter = new CustomAdapter(context);
mViewPager.setAdapter(adapter);
mViewPager.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

ありがとう。これはうまくいきました。しかし、なぜAndroidチームはこれをコードベースに含めることができないのでしょうか?
モハナクリシュナ

これは、必要に応じて自分でカスタマイズする必要があるものの1つであり、Googleが今年2019年のGoogle I / OでviewPager2を導入しました。これは、2011年に作成された古いViewPagerの置き換えであり、実装は「androidx.viewpager2:viewpager2」です。 :1.0.0-alpha04 '
Hossam Hassan

2

選択したアイテムに応じてビューページャーが高さを変更するようにcybergenの回答を編集します。クラスはcybergenと同じですが、すべてのビューページャーの子ビューの高さである整数のベクターを追加しました。ページを変更して高さを更新すると、アクセスできます。

これはクラスです:

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import java.util.Vector;

public class WrapContentHeightViewPager extends ViewPager {
    private Vector<Integer> heights = new Vector<>();

    public WrapContentHeightViewPager(@NonNull Context context) {
        super(context);
    }

    public WrapContentHeightViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        for(int i=0;i<getChildCount();i++) {
            View view = getChildAt(i);
            if (view != null) {
                view.measure(widthMeasureSpec, heightMeasureSpec);
                heights.add(measureHeight(heightMeasureSpec, view));
            }
        }
        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, getChildAt(0)));
    }

    public int getHeightAt(int position){
        return heights.get(position);
    }

    private int measureHeight(int measureSpec, View view) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            if (view != null) {
                result = view.getMeasuredHeight();
            }
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }
}

次に、アクティビティにOnPageChangeListenerを追加します

WrapContentHeightViewPager viewPager = findViewById(R.id.my_viewpager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
     @Override
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
     @Override
     public void onPageSelected(int position) {
         LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) viewPager.getLayoutParams();
         params.height = viewPager.getHeightAt(position);
         viewPager.setLayoutParams(params);
     }
     @Override
     public void onPageScrollStateChanged(int state) {}
});

そしてここにxmlがあります:

<com.example.example.WrapContentHeightViewPager
    android:id="@+id/my_viewpager"
    android:fillViewport="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

必要に応じて英語を修正してください


これにはいくつかの問題があります。heightsリストは無限大を増大させることができます。
rosuh

@rosuh問題が発生したのはいつですか?これをViewPagerのTabLayoutでのみ使用したため、どこでもうまく機能するかどうかはわかりません
geggiamarti

@geggiamarti問題は、一部のページがリサイクルされることです。そして、ユーザーがそれらにスワイプしたときに再作成されるため、measure複数回呼び出されます。高さリストを増やす可能性があります。別の状況では、ユーザーがこのviewPagerに対して手動でrequestLayout(またはsetLayoutParamsメソッドと同じように)呼び出し、複数回測定する場合もあります。
rosuh

1

場合ViewPagerあなたが使用しているが、の子であるScrollView 持っているPagerTitleStrip子供をすでに提供偉大な答えの若干の修正を使用する必要があります。参考までに、私のXMLは次のようになります。

<ScrollView
    android:id="@+id/match_scroll_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white">

    <LinearLayout
        android:id="@+id/match_and_graphs_wrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <view
            android:id="@+id/pager"
            class="com.printandpixel.lolhistory.util.WrapContentHeightViewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v4.view.PagerTitleStrip
                android:id="@+id/pager_title_strip"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:background="#33b5e5"
                android:paddingBottom="4dp"
                android:paddingTop="4dp"
                android:textColor="#fff" />
        </view>
    </LinearLayout>
</ScrollView>

あなたの中で、もしあれば、測定された高さonMeasure追加する必要がPagerTitleStripあります。それ以外の場合、その高さは、追加のスペースを占有しますが、すべての子の最大の高さとは見なされません。

これが他の誰かを助けることを願っています。少しハックされて申し訳ありません...

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 pagerTitleStripHeight = 0;
        int height = 0;
        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) {
                // get the measuredHeight of the tallest fragment
                height = h;
            }
            if (child.getClass() == PagerTitleStrip.class) {
                // store the measured height of the pagerTitleStrip if one is found. This will only
                // happen if you have a android.support.v4.view.PagerTitleStrip as a direct child
                // of this class in your XML.
                pagerTitleStripHeight = h;
            }
        }

        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height+pagerTitleStripHeight, MeasureSpec.EXACTLY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

1

ここで私が目にするソリューションのほとんどは、二重の測定を行っているようです。最初に子ビューを測定してから、 super.onMeasure()

WrapContentViewPagerより効率的でRecyclerViewとFragmentでうまく機能するカスタムを思いついた

ここでデモを確認できます。

github / ssynhtn / WrapContentViewPager

ここのクラスのコード: WrapContentViewPager.java


0

私は似ていますが、より複雑なシナリオです。ViewPagerを含むダイアログがあります。
子ページの1つが短く、高さが一定しています。
別の子ページは常にできるだけ高くする必要があります。
別の子ページにはScrollViewが含まれており、ScrollViewのコンテンツがダイアログで利用できる高さ全体を必要としない場合、ページ(つまりダイアログ全体)はWRAP_CONTENTでなければなりません。

この特定のシナリオでは、既存の回答のいずれも完全に機能しませんでした。ちょっと待って-でこぼこの乗り物です。

void setupView() {
    final ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            currentPagePosition = position;

            // Update the viewPager height for the current view

            /*
            Borrowed from https://github.com/rnevet/WCViewPager/blob/master/wcviewpager/src/main/java/nevet/me/wcviewpager/WrapContentViewPager.java
            Gather the height of the "decor" views, since this height isn't included
            when measuring each page's view height.
             */
            int decorHeight = 0;
            for (int i = 0; i < viewPager.getChildCount(); i++) {
                View child = viewPager.getChildAt(i);
                ViewPager.LayoutParams lp = (ViewPager.LayoutParams) child.getLayoutParams();
                if (lp != null && lp.isDecor) {
                    int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
                    boolean consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM;
                    if (consumeVertical) {
                        decorHeight += child.getMeasuredHeight();
                    }
                }
            }

            int newHeight = decorHeight;

            switch (position) {
                case PAGE_WITH_SHORT_AND_STATIC_CONTENT:
                    newHeight += measureViewHeight(thePageView1);
                    break;
                case PAGE_TO_FILL_PARENT:
                    newHeight = ViewGroup.LayoutParams.MATCH_PARENT;
                    break;
                case PAGE_TO_WRAP_CONTENT:
//                  newHeight = ViewGroup.LayoutParams.WRAP_CONTENT; // Works same as MATCH_PARENT because...reasons...
//                  newHeight += measureViewHeight(thePageView2); // Doesn't allow scrolling when sideways and height is clipped

                    /*
                    Only option that allows the ScrollView content to scroll fully.
                    Just doing this might be way too tall, especially on tablets.
                    (Will shrink it down below)
                     */
                    newHeight = ViewGroup.LayoutParams.MATCH_PARENT;
                    break;
            }

            // Update the height
            ViewGroup.LayoutParams layoutParams = viewPager.getLayoutParams();
            layoutParams.height = newHeight;
            viewPager.setLayoutParams(layoutParams);

            if (position == PAGE_TO_WRAP_CONTENT) {
                // This page should wrap content

                // Measure height of the scrollview child
                View scrollViewChild = ...; // (generally this is a LinearLayout)
                int scrollViewChildHeight = scrollViewChild.getHeight(); // full height (even portion which can't be shown)
                // ^ doesn't need measureViewHeight() because... reasons...

                if (viewPager.getHeight() > scrollViewChildHeight) { // View pager too tall?
                    // Wrap view pager height down to child height
                    newHeight = scrollViewChildHeight + decorHeight;

                    ViewGroup.LayoutParams layoutParams2 = viewPager.getLayoutParams();
                    layoutParams2.height = newHeight;
                    viewPager.setLayoutParams(layoutParams2);
                }
            }

            // Bonus goodies :)
            // Show or hide the keyboard as appropriate. (Some pages have EditTexts, some don't)
            switch (position) {
                // This case takes a little bit more aggressive code than usual

                if (position needs keyboard shown){
                    showKeyboardForEditText();
                } else if {
                    hideKeyboard();
                }
            }
        }
    };

    viewPager.addOnPageChangeListener(pageChangeListener);

    viewPager.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // http://stackoverflow.com/a/4406090/4176104
                    // Do things which require the views to have their height populated here
                    pageChangeListener.onPageSelected(currentPagePosition); // fix the height of the first page

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        viewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        viewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }

                }
            }
    );
}


...

private void showKeyboardForEditText() {
    // Make the keyboard appear.
    getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    inputViewToFocus.requestFocus();

    // http://stackoverflow.com/a/5617130/4176104
    InputMethodManager inputMethodManager =
            (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.toggleSoftInputFromWindow(
            inputViewToFocus.getApplicationWindowToken(),
            InputMethodManager.SHOW_IMPLICIT, 0);
}

...

/**
 * Hide the keyboard - http://stackoverflow.com/a/8785471
 */
private void hideKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

    inputManager.hideSoftInputFromWindow(inputBibleBookStart.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

...

//https://github.com/rnevet/WCViewPager/blob/master/wcviewpager/src/main/java/nevet/me/wcviewpager/WrapContentViewPager.java
private int measureViewHeight(View view) {
    view.measure(ViewGroup.getChildMeasureSpec(-1, -1, view.getLayoutParams().width), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    return view.getMeasuredHeight();
}

ビューを測定し、装飾の高さを測定するコードを提供してくれた@Raananに感謝します。私は彼のライブラリで問題に遭遇しました-アニメーションが途切れる、そしてダイアログの高さがそれを必要とするのに十分に短い場合、私のScrollViewはスクロールしないと思います。


0

私の場合、追加clipToPaddingすると問題が解決しました。

<android.support.v4.view.ViewPager
    ...
    android:clipToPadding="false"
    ...
    />

乾杯!



0

私の場合、サイズを適用するときに、現在選択されている要素とアニメーションのwrap_contentを持つビューページャーが必要でした。以下に私の実装を示します。誰かが重宝しますか?

package one.xcorp.widget

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import one.xcorp.widget.R
import kotlin.properties.Delegates.observable

class ViewPager : android.support.v4.view.ViewPager {

    var enableAnimation by observable(false) { _, _, enable ->
        if (enable) {
            addOnPageChangeListener(onPageChangeListener)
        } else {
            removeOnPageChangeListener(onPageChangeListener)
        }
    }

    private var animationDuration = 0L
    private var animator: ValueAnimator? = null

    constructor (context: Context) : super(context) {
        init(context, null)
    }

    constructor (context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.ViewPager,
            0,
            0
        ).apply {
            try {
                enableAnimation = getBoolean(
                    R.styleable.ViewPager_enableAnimation,
                    enableAnimation
                )
                animationDuration = getInteger(
                    R.styleable.ViewPager_animationDuration,
                    resources.getInteger(android.R.integer.config_shortAnimTime)
                ).toLong()
            } finally {
                recycle()
            }
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)

        val measuredHeight = if (heightMode == MeasureSpec.EXACTLY) {
            MeasureSpec.getSize(heightMeasureSpec)
        } else {
            val currentViewHeight = findViewByPosition(currentItem)?.also {
                measureView(it)
            }?.measuredHeight ?: 0

            if (heightMode != MeasureSpec.AT_MOST) {
                currentViewHeight
            } else {
                Math.min(
                    currentViewHeight,
                    MeasureSpec.getSize(heightMeasureSpec)
                )
            }
        }

        super.onMeasure(
            widthMeasureSpec,
            MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.EXACTLY)
        )
    }

    private fun measureView(view: View) = with(view) {
        val horizontalMode: Int
        val horizontalSize: Int
        when (layoutParams.width) {
            MATCH_PARENT -> {
                horizontalMode = MeasureSpec.EXACTLY
                horizontalSize = this@ViewPager.measuredWidth
            }
            WRAP_CONTENT -> {
                horizontalMode = MeasureSpec.UNSPECIFIED
                horizontalSize = 0
            }
            else -> {
                horizontalMode = MeasureSpec.EXACTLY
                horizontalSize = layoutParams.width
            }
        }

        val verticalMode: Int
        val verticalSize: Int
        when (layoutParams.height) {
            MATCH_PARENT -> {
                verticalMode = MeasureSpec.EXACTLY
                verticalSize = this@ViewPager.measuredHeight
            }
            WRAP_CONTENT -> {
                verticalMode = MeasureSpec.UNSPECIFIED
                verticalSize = 0
            }
            else -> {
                verticalMode = MeasureSpec.EXACTLY
                verticalSize = layoutParams.height
            }
        }

        val horizontalMeasureSpec = MeasureSpec.makeMeasureSpec(horizontalSize, horizontalMode)
        val verticalMeasureSpec = MeasureSpec.makeMeasureSpec(verticalSize, verticalMode)

        measure(horizontalMeasureSpec, verticalMeasureSpec)
    }

    private fun findViewByPosition(position: Int): View? {
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            val childLayoutParams = childView.layoutParams as LayoutParams

            val childPosition by lazy {
                val field = childLayoutParams.javaClass.getDeclaredField("position")
                field.isAccessible = true
                field.get(childLayoutParams) as Int
            }

            if (!childLayoutParams.isDecor && position == childPosition) {
                return childView
            }
        }

        return null
    }

    private fun animateContentHeight(childView: View, fromHeight: Int, toHeight: Int) {
        animator?.cancel()

        if (fromHeight == toHeight) {
            return
        }

        animator = ValueAnimator.ofInt(fromHeight, toHeight).apply {
            addUpdateListener {
                measureView(childView)
                if (childView.measuredHeight != toHeight) {
                    animateContentHeight(childView, height, childView.measuredHeight)
                } else {
                    layoutParams.height = animatedValue as Int
                    requestLayout()
                }
            }
            duration = animationDuration
            start()
        }
    }

    private val onPageChangeListener = object : OnPageChangeListener {

        override fun onPageScrollStateChanged(state: Int) {
            /* do nothing */
        }

        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            /* do nothing */
        }

        override fun onPageSelected(position: Int) {
            if (!isAttachedToWindow) {
                return
            }

            findViewByPosition(position)?.let { childView ->
                measureView(childView)
                animateContentHeight(childView, height, childView.measuredHeight)
            }
        }
    }
}

プロジェクトにattrs.xmlを追加します。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ViewPager">
        <attr name="enableAnimation" format="boolean" />
        <attr name="animationDuration" format="integer" />
    </declare-styleable>
</resources>

そして使用:

<one.xcorp.widget.ViewPager
    android:id="@+id/wt_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:enableAnimation="true" />

0

このViewPagerは、現在表示されている子のみにサイズ変更します(実際の子の最大ではありません)。

https://stackoverflow.com/a/56325869/4718406のアイデア

public class DynamicHeightViewPager extends ViewPager {

public DynamicHeightViewPager (Context context) {
    super(context);
    initPageChangeListener();
}

public DynamicHeightViewPager (Context context, AttributeSet attrs) {
    super(context, attrs);
    initPageChangeListener();
}



private void initPageChangeListener() {
    addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            requestLayout();
        }
    });
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //View child = getChildAt(getCurrentItem());
    View child = getCurrentView(this);
    if (child != null) {
        child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, 
         MeasureSpec.UNSPECIFIED));
        int h = child.getMeasuredHeight();

        heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}


View getCurrentView(ViewPager viewPager) {
    try {
        final int currentItem = viewPager.getCurrentItem();
        for (int i = 0; i < viewPager.getChildCount(); i++) {
            final View child = viewPager.getChildAt(i);
            final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) 
             child.getLayoutParams();

            Field f = layoutParams.getClass().getDeclaredField("position"); 
            //NoSuchFieldException
            f.setAccessible(true);
            int position = (Integer) f.get(layoutParams); //IllegalAccessException

            if (!layoutParams.isDecor && currentItem == position) {
                return child;
            }
        }
    } catch (NoSuchFieldException e) {
        e.fillInStackTrace();
    } catch (IllegalArgumentException e) {
        e.fillInStackTrace();
    } catch (IllegalAccessException e) {
        e.fillInStackTrace();
    }
    return null;
}

}


0

ViewPagerの高さを測定します。

public class WrapViewPager extends ViewPager {
    View primaryView;

    public WrapViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (primaryView != null) {
            int height = 0;
            for (int i = 0; i < getChildCount(); i++) {
                if (primaryView == getChildAt(i)) {
                    int childHeightSpec = MeasureSpec.makeMeasureSpec(0x1 << 30 - 1, MeasureSpec.AT_MOST);
                    getChildAt(i).measure(widthMeasureSpec, childHeightSpec);
                    height = getChildAt(i).getMeasuredHeight();
                }

            }

            setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        }
    }

    public void setPrimaryView(View view) {
        primaryView = view;
    }

}

setPrimaryView(View)を呼び出します:

public class ZGAdapter extends PagerAdapter {

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        ((WrapViewPager)container).setPrimaryView((View)object);
    }

}

0

ViewPagerの親レイアウトを NestedScrollView

   <androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:fillViewport="true">
        <androidx.viewpager.widget.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </androidx.viewpager.widget.ViewPager>
    </androidx.core.widget.NestedScrollView>

設定することを忘れないでください android:fillViewport="true"

これにより、scrollviewとその子のコンテンツがビューポートいっぱいに拡大されます。

https://developer.android.com/reference/android/widget/ScrollView.html#attr_android:fillViewport


0

ViewPager2に切り替えることができます。これは、ViewPagerの更新バージョンです。ViewPagerと同じことを行いますが、よりスマートで効率的な方法です。ViewPager2には、さまざまな新機能が搭載されています。もちろん、コンテンツのラップの問題はViewPager2によって解決されています。

Androidのドキュメントから:「ViewPager2はViewPagerに取って代わり、右から左へのレイアウトサポート、垂直方向、変更可能なFragmentコレクションなどを含む、以前のほとんどの問題点に対処します。」

私はこの記事を初心者にお勧めします:

https://medium.com/google-developer-experts/exploring-the-view-pager-2-86dbce06ff71


この問題はまだ存在します。issuetracker.google.com
u /
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.