Is there really no clean way to programmatically add scrollbars to a custom view?

若如初见. 提交于 2019-12-02 21:57:54

问题


I want to add scrollbars to my custom view programmatically. Before Lollipop, this was done in the constructor like so:

setHorizontalScrollBarEnabled(true);
setVerticalScrollBarEnabled(true);

TypedArray a = context.obtainStyledAttributes(R.styleable.View);
initializeScrollbars(a);
a.recycle();

(see here)

Now with the introduction of Lollipop, Google made the initializeScrollbars() API private so it's no longer available (see here)

So people have suggested to just manually import initializeScrollbars() and call it, like so:

final TypedArray a = context.getTheme().obtainStyledAttributes(new int[0]);
try {
    // initializeScrollbars(TypedArray)
    Method initializeScrollbars = android.view.View.class.getDeclaredMethod("initializeScrollbars", TypedArray.class);
    initializeScrollbars.invoke(this, a);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
    e.printStackTrace();
}
a.recycle();

This does the trick but of course it's a hack.

So does this mean that more than 4 years after the introduction of Lollipop and the removal of initializeScrollbars() it is still impossible to programmatically add scrollbars to a custom view and that the only safe way to do that is to inflate an XML or is there a clean solution to do this in the meanwhile?

It's hard to imagine for Google to remove initializeScrollbars() without providing an alternative way to do what it does... especially since it has been 4 years now and adding scrollbars to a custom view looks like a rather common task so I'm really puzzled why this is apparently so complicated to achieve programmatically.

来源:https://stackoverflow.com/questions/52916047/is-there-really-no-clean-way-to-programmatically-add-scrollbars-to-a-custom-view

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