重置Android textview maxlines

jex*_*xcy 48 android textview

我想创建一个可以通过用户触摸折叠的TextView.当TextView折叠时,我设置了textView.setMaxLines(4);.如何在我的expand方法中清除此状态?我只能想到setMaxLines()一个像10000这样的值大号的调用.

有没有更好的方法来实现这一点?

Val*_*mar 100

实际上,android平台的做法是将MaxLine设置为Integer.MAX_VALUE.

textView.setMaxLines(Integer.MAX_VALUE);
Run Code Online (Sandbox Code Playgroud)

另外,如果您使用的是Ellipsize,请不要忘记设置为null.

textView.setEllipsize(null);
Run Code Online (Sandbox Code Playgroud)

只检查android框架是如何做到的;)观察setMaxLines(Integer.MAX_VALUE);

private void applySingleLine(boolean singleLine, boolean applyTransformation) {
    mSingleLine = singleLine;
    if (singleLine) {
        setLines(1);
        setHorizontallyScrolling(true);
        if (applyTransformation) {
            setTransformationMethod(SingleLineTransformationMethod.getInstance());
        }
       } else {
            setMaxLines(Integer.MAX_VALUE);
            setHorizontallyScrolling(false);
            if (applyTransformation) {
                 setTransformationMethod(null);
        }
       }
     }
Run Code Online (Sandbox Code Playgroud)

你可以在Android开源项目(AOSP)的源代码中找到这个

https://source.android.com/source/downloading

如果您不想下载源代码,可以在github上的镜像上查看源代码.

https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/widget/TextView.java

  • 万一有人像我一样碰到这个:1)我不会在第一部分使用setLines但是使用setMaxLines(1)代替.2)setEllipsize为null非常重要,以便在旧的Android版本中扩展视图3)getLineCount(来自其他答案)从我的经验来看并不是非常可靠. (3认同)

bes*_*dze 5

试试这个(infoView.getLineCount()):

public void onMoreClick(View v) {
    Button btn = (Button) v;
    if(!moreSwitcher) {
        infoView.setMaxLines(infoView.getLineCount());
        infoView.setLines(infoView.getLineCount());
        moreSwitcher = true;
        btn.setText(R.string.collapse);
    }else{
        infoView.setMaxLines(5);
        infoView.setLines(5);
        moreSwitcher = false;
        btn.setText(R.string.expand);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 重置`setLines()`最正确的方法是调用`setMinLines(0)`,然后调用`setMaxLines(Integer.MAX_VALUE)`(如果`scrollHorizo​​ntally`设置为true,这不起作用) (2认同)