Non ero molto contento la risposta accettata (né con la soluzione pre-gonfia-all-views nei commenti), quindi ho messo insieme uno ViewPager
che prende la sua altezza dal primo figlio disponibile. Lo fa facendo un secondo passaggio di misurazione, permettendoti di rubare l'altezza del primo bambino.
Una migliore soluzione sarebbe quella di effettuare una nuova classe all'interno dell'imballaggio android.support.v4.view
che implementa una versione migliore di onMeasure
(con accesso a metodi del pacchetto visibile come populate()
)
Per il momento, però, la soluzione qui di seguito mi sta bene
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);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec)
== MeasureSpec.AT_MOST;
if(wrapHeight) {
/**
* The first super.onMeasure call made the pager take up all the
* available height. Since we really wanted to wrap it, we need
* to remeasure it. Luckily, after that call the first child is
* now available. So, we take the height from it.
*/
int width = getMeasuredWidth(), height = getMeasuredHeight();
// Use the previously measured width but simplify the calculations
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
/* If the pager actually has any children, take the first child's
* height and call that our own */
if(getChildCount() > 0) {
View firstChild = getChildAt(0);
/* The child was previously measured with exactly the full height.
* Allow it to wrap this time around. */
firstChild.measure(widthMeasureSpec,
MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST));
height = firstChild.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
prega protagonista problema https://code.google.com/p/android/issues/detail?id=54604 – Christ
FYI: Il problema 54604 è stato chiuso alla rinfusa da Google ieri. Se hai ancora il problema, ti suggerisco di riaprire un nuovo problema e inserire il link qui. – Christ
possibile duplicato di [Android: non riesco ad avere ViewPager WRAP \ _CONTENT] (http://stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content) – Raanan