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

时间:2017-07-27 18:38:51

标签: textview android-nestedscrollview android

我在NestedScrollView内有一个ScrollViewNestedScrollView包含TextView。因此,当TextView扩展到4以上或 n 线条时,我需要将其设为Scrollable TextView

非常感谢任何帮助!!

2 个答案:

答案 0 :(得分:1)

我希望你现在必须解决这个问题。如果将来有人查找,您无需设置最大高度。只需将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 :(得分:0)

我遇到了同样的问题,固定高度无济于事,因为它可能比我的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);
    }
}