I have a custom View class that extends Spinner. I'm trying to figure out what the correct way to talk to the Activity that it's embedded in is, when the user makes a selection. I see that the OnItemSelected
listener gets a reference to the Adapter, but I'm not clear on whether or not I should be using this adapter and walking up its parent chain somehow, or if I should just talk directly to the context (for some reason that doesn't feel safe, even though I can't think of a way in which it might fail, offhand).
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
You don't want to "talk to the Activity that it's embedded in". You want to talk to the controller responsible for the
View
. Today, that might be anActivity
. Tomorrow, that might be aFragment
.That implies that the
View
knows the specific type ofAdapter
, since theAdapter
interface does not have any sort ofgetContext()
method. Moreover, it ties you to talking to theActivity
, which is not a good plan at this point, as mentioned above.Personally, I'm a bit dubious about having a custom
Spinner
subclass in the first place. But, assuming there's a good reason for it, you should follow Tal Kanel's advice (posted while I was writing this) and design a custom listener interface for this custom event that is being declared by your customView
. Have the controller (Activity
orFragment
) supply an implementation of that interface -- this could be directly implemented on the controller, or implemented as an anonymous inner class (as in Tal Kanel's answer), etc. Have your customView
call method(s) on the listener interface as needed.the right way to do that, is to "listen" to your custom view by exposing an interface which your view holding a reference to instance of him, and you hosting activity should implement. exactly like the OnItemSelected interface and any events which android views are exposing is been implemented. this is the observer design pattern.
for example:
this is how you will use it from your activity:
A simple solution -
Where ParentClass is the class name of the activity.
The correct way is using a listener of some sort. I think you can make direct reference, your code would just not be reusable for another project then...