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

非 Y 不嫁゛ 提交于 2020-01-01 16:38:19

问题


I used TextView#getMaxLines() in my application for a few weeks without incident.

Lint is now informing me that it's only available in API 16+ (#setMaxLines() is API 1+...), though (to the best of my knowledge) I haven't modified anything that would cause this sudden flag - my min-sdk has been 8 for a while, and I have files in my source control to prove it.

1) Why could lint be flagging this error randomly? (To be clear, I mean to say that it should have caught it initially - I'm not implying this is something that it shouldn't have flagged at all).

2) Is there any way to retrieve the maxLines for a TextView on pre-api 16 devices? I checked the source but couldn't devise a way to retrieve this value using the exposed methods on a 2.2 device.


回答1:


A simpler solution was added to the support lib v4 inTextViewCompat

int maxLines = TextViewCompat.getMaxLines(yourtextView);

Check out this answer for some more informations.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/16255480/is-it-possible-to-textviewgetmaxlines-on-pre-api-16-devices

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