8

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!!

Community
  • 1
  • 1
I. A
  • 1,938
  • 17
  • 47

2 Answers2

1

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);
    }
}
Rodrigo Butzke
  • 428
  • 3
  • 14
  • This scrollview will only work when minHeight is set from Java code, as it does not specify how to read "minHeight" attribute value from xml. – Akhilesh Kumar Jan 16 '20 at 09:12
0

I hope you must have solved this issue by now. If someone looks for it in the future, you don't need to set maximum height. Just set the height of NestedScrollView to say 37f and whenever the text size goes above 37, the NestedScrollView would start scrolling.

xml:

<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
        android:layout_height="wrap_content">
...
</android.support.v4.widget.NestedScrollView>

or programatically:

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);
Sahil Wadhwa
  • 35
  • 1
  • 4