问题
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!!
回答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);
}
}
回答2:
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);
来源:https://stackoverflow.com/questions/45358648/how-to-set-the-maximum-height-for-a-nestedscrollview-in-android