Is there really no clean way to programmatically a

2020-05-02 04:09发布

问题:

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.