How can I set the max height for a NestedScrollView in Android?
2 answers
Hopefully you should be able to resolve this issue. If anyone is looking for it in the future, you don't need to set the maximum height. Just set the height of the NestedScrollView to say 37f, and whenever the text size exceeds 37, the NestedScrollView will start scrolling.
XML:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
...
</android.support.v4.widget.NestedScrollView>
or programmatically:
NestedScrollView nsv = new NestedScrollView(getActivity());
// Initialize Layout Parameters
RelativeLayout.LayoutParams nsvParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 38));
// Set Layout Parameters
nsv.setLayoutParams(nsvParams);
0
source to share
I faced the same problem and fixed height won't help because it might 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);
}
}
0
source to share