I'm writing a custom view that directly extends android.view.View
. If I try to access fields mScrollX
or mScrollY
, I see an error that the field "cannot be resolved or is not a field." The source code for android.view.View has mScrollX, mScrollY, and similar variables declared protected
. How is it that my direct subclass cannot access protected fields of its parent class? (Classes like ScrollView apparently can.)
P.S. I realize that I can call getScrollX()
, but I want to update these fields; calling setScroll()
has side effects that I don't want.
Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
protected allows you access from the same package, or parent classes. protected allows access within the same package, or by subclasses. Neither is the case when using a superclass object reference.
The protected Keyword While elements declared as private can be accessed only by the class in which they're declared, the protected keyword allows access from sub-classes and members of the same package.
No because the compiler does not know whether b is an instance of B , C , or other external classes.
It's because they are not part of the Android SDK.
Here is the source code for mScrollX
:
/**
* The offset, in pixels, by which the content of this view is scrolled
* horizontally.
* {@hide}
*/
@ViewDebug.ExportedProperty(category = "scrolling")
protected int mScrollX;
You will notice the @hide
annotation. That means this is not part of the Android SDK. The part of the build process that creates the Android SDK will not include this data member in the stub edition of android.view.View
that is in the android.jar
file that you are compiling against.
The @hide
annotation is used for things that for internal purposes needed to be public or protected but are not considered something SDK developers should be using.
Please find other solutions for whatever problem you are experiencing.
It's very straight forward: notice the @hide annotation above these variables. It's an Android-specific annotation that hides the fields/methods from the public SDK. That's why you can't access them directly.
Romain Guy mentioned it in this post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With