如何在 Android 中为 NestedScrollView 设置最大高度? [英] How to set the Maximum Height for a NestedScrollView in Android?

查看:269
本文介绍了如何在 Android 中为 NestedScrollView 设置最大高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ScrollView 中有一个 NestedScrollView.NestedScrollView 包含一个 TextView.因此,当 TextView 扩展到 4 或 n 行以上时,我需要使其成为 Scrollable TextView.

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.

非常感谢任何帮助!

推荐答案

我遇到了同样的问题,固定高度无济于事,因为它可能比我的 TextView 大,所以我创建了这个类

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

这篇关于如何在 Android 中为 NestedScrollView 设置最大高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆