Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Maximum Height for a NestedScrollView in Android?

I have a NestedScrollView within a ScrollView. the NestedScrollView contains a TextView. So when the TextView expands above 4 or n lineas, I need to make it Scrollable TextView.

Any help is much appreciated!!

like image 465
I. A Avatar asked Jul 27 '17 18:07

I. A


1 Answers

I have face the same problem, and a fixed height wouldn't help because it could be bigger than my TextView, so i created this class

import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

public class MaxHeightNestedScrollView extends NestedScrollView {

    private int maxHeight = -1;

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

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

    public MaxHeightNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public int getMaxHeight() {
        return maxHeight;
    }

    public void setMaxHeight(int maxHeight) {
        this.maxHeight = maxHeight;
    }

    public void setMaxHeightDensity(int dps){
        this.maxHeight = (int)(dps * getContext().getResources().getDisplayMetrics().density);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
like image 70
Rodrigo Butzke Avatar answered Nov 15 '22 00:11

Rodrigo Butzke