Как установить максимальную высоту с содержимым переноса в Android?

В Android, как вы можете создать представление прокрутки, которое имеет максимальную высоту, и обернуть содержимое, в основном оно оборачивает содержимое по вертикали, но имеет максимальную высоту?

Я старался

<ScrollView 
     android:id="@+id/scrollView1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
         android:maxHeight="200dp"
     android:layout_alignParentBottom="true" >

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

    </LinearLayout>
</ScrollView>

Но это не работает?

5 ответов

Вы можете добавить это к любому представлению (переопределить onMeasure в классе, унаследованном от представления)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (maxHeight > 0){
        int hSize = MeasureSpec.getSize(heightMeasureSpec);
        int hMode = MeasureSpec.getMode(heightMeasureSpec);

        switch (hMode){
            case MeasureSpec.AT_MOST:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.AT_MOST);
                break;
            case MeasureSpec.UNSPECIFIED:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
                break;
            case MeasureSpec.EXACTLY:
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.EXACTLY);
                break;
        }
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Я расширил ScrollView и добавил код для реализации этой функции:

https://gist.github.com/JMPergar/439aaa3249fa184c7c0c

Я надеюсь, что это будет полезно.

Вы можете сделать это программно.

 private static class OnViewGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private final static int maxHeight = 130;
    private View view;

    public OnViewGlobalLayoutListener(View view) {
        this.view = view;
    }

    @Override
    public void onGlobalLayout() {
        if (view.getHeight() > maxHeight)
            view.getLayoutParams().height = maxHeight;
    }
}

И добавьте слушателя к представлению:

view.getViewTreeObserver()
                  .addOnGlobalLayoutListener(new OnViewGlobalLayoutListener(view));

Слушатель вызовет метод onGlobalLayout(), когда будет изменена высота просмотра.

Это можно сделать, обернув представление в ConstraintLayout и используяlayout_constraintHeight_max атрибут.

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_max="wrap"
        app:layout_constraintVertical_bias="0">

        ...

    </ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

В приведенном выше примере родительский ConstraintLayout высота ограничена 200dp, и ребенок ScrollView height оборачивает содержимое, пока оно не станет меньше 200dp. Обратите внимание, чтоapp:layout_constraintVertical_bias="0" выравнивает ребенка ScrollView вверху родителя, иначе он будет центрирован.

1.) Создайте класс для обработки установки максимальной высоты, которую передает пользователь:

public class OnViewGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {


private Context context;
private int maxHeight;
private View view;

public OnViewGlobalLayoutListener(View view, int maxHeight, Context context) {
    this.context = context;
    this.view = view;
    this.maxHeight = dpToPx(maxHeight);
}

@Override
public void onGlobalLayout() {
    if (view.getHeight() > maxHeight) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = maxHeight;
        view.setLayoutParams(params);
    }
}

public int pxToDp(int px) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return dp;
}

public int dpToPx(int dp) {
    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
    return px;
}
}

2.) Прикрепите это к виду и передайте максимальную высоту в DP:

messageBody.getViewTreeObserver()
            .addOnGlobalLayoutListener(
             new OnViewGlobalLayoutListener(messageBody, 256, context)
             );

Спасибо @harmashalex за вдохновение. Я внес изменения в настройку параметров макета, которые не работали в коде @harma. Кроме того, преобразование dp-to-px необходимо, чтобы избавиться от недоумения.

Для установки высоты просмотра прокрутки вы должны использовать 2 внутренних слоя вместе, а затем установить представление scrool как их потомок, а затем установить макет среднего размера внутреннего слоя: высоту для ограничения высоты просмотра прокрутки.

Здесь вы можете установить высоту вашего Scrollview следующим образом:

<ScrollView 
 android:id="@+id/scrollView1"
 android:layout_width="match_parent"
 android:layout_height="200dp"
 android:layout_alignParentBottom="true" >

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

           </LinearLayout>
</ScrollView>
Другие вопросы по тегам