如何在Android中为NestedScrollView设置最大高度?

8
我有一个NestedScrollViewScrollView内部。 NestedScrollView 包含一个TextView。因此,当TextView 超过4行或n行时,我需要将其变为可滚动的TextView
非常感谢您的任何帮助!
2个回答

1

我遇到了相同的问题,固定高度无法解决问题,因为它可能比我的TextView更大,所以我创建了这个类。

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);
    }
}

当从XML中读取“minHeight”属性值时,此ScrollView仅在Java代码中设置了minHeight才能正常工作。 - Akhilesh Kumar

0
我希望你现在一定已经解决了这个问题。如果将来有人寻找该解决方案,你无需设置最大高度。只需将NestedScrollView的高度设置为37f,并且每当文本大小超过37时,NestedScrollView就会开始滚动。
xml:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
        android:layout_height="wrap_content">
...
</android.support.v4.widget.NestedScrollView>

或者通过编程方式:

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);

1
这会设置一个高度,而不是最大高度。 - Rodrigo Butzke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接