Is it possible to TextView#getMaxLines() on pre api-16 devices?

你说的曾经没有我的故事 提交于 2019-12-04 14:34:28
daemmie

A simpler solution was added to the support lib v4 inTextViewCompat

int maxLines = TextViewCompat.getMaxLines(yourtextView);

Check out this answer for some more informations.

You can use Reflection:

Field mMaximumField = null;
Field mMaxModeField = null;
try {
    mMaximumField = text.getClass().getDeclaredField("mMaximum");
    mMaxModeField = text.getClass().getDeclaredField("mMaxMode");
} catch (NoSuchFieldException e) {
    e.printStackTrace();
}

if (mMaximumField != null && mMaxModeField != null) {
    mMaximumField.setAccessible(true);
    mMaxModeField.setAccessible(true);

    try {
        final int mMaximum = mMaximumField.getInt(text); // Maximum value
        final int mMaxMode = mMaxModeField.getInt(text); // Maximum mode value

        if (mMaxMode == 1) { // LINES is 1
            text.setText(Integer.toString(mMaximum));
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

OR:

Maybe, the best way is keep maxLine value at values and set it value in xml, and get as int resource in code.

The code for that method simply doesn't exist on 2.2, so you can't use it directly of course.

On the other hand, I've run a diff on the two files and it seems as though the new 4.2.2 TextView isn't using any new APIs internally (this is based solely on its imports). You may be able to add it as a class in your project and use it instead of the inbuilt TextView across all version of Android.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!