在android中访问重写方法的参数的子方法?
这一定是一个菜鸟问题,但我找不到适当的等待来实现以下目标:
在android中,我创建了一个扩展View类的子类MyView。在 B 中,我定义了 View 类中不存在的方法 mMethod。
现在,我想在 MyView 上设置一个 OnClickListener 接口。为此,我必须在定义新的 OnClickListener 时重写 onClick 方法。此外,我想访问 onClick 中的 mMethod 方法,但重写的方法需要一个 View 类实例,而不是 MyView 的实例。那我能做什么呢?
更准确地说:
public class MyView extends View{
...
public void mMethod(){
...
}
}
在主类(Activity)中
MyView myView = new MyView ()
//It's not the correct constructor, but it's not the point
myView.setOnClickListener(new OnClickListener(){
@Override
public boolean onClick(View v){
//Here I would like to access mMethod of MyView
???
}
}
使用 myView.mMethod() 是唯一的解决方案吗?是否可以将 v
向下转换为 (MyView)v
?如果是这样,该怎么办?我应该定义一个子接口吗?
谢谢你!
This must be a noob question, but I can't find the proper wait to achieve the following:
In android, I made a subclass MyView extending a View class. In B, I've defined a method mMethod not present in the View class.
Now, I want to set an OnClickListener interface on MyView. Doing this, I must override a onClick method when defining a new OnClickListener. Furthermore, I would like to access the mMethod method in onClick, but the overriden method is expecting a View class instance, not a MyView's one. So what can I do ?
To be more precise:
public class MyView extends View{
...
public void mMethod(){
...
}
}
And in the main class (Activity)
MyView myView = new MyView ()
//It's not the correct constructor, but it's not the point
myView.setOnClickListener(new OnClickListener(){
@Override
public boolean onClick(View v){
//Here I would like to access mMethod of MyView
???
}
}
Is using myView.mMethod()
is the only solution ? Is it possible to downcast v
to (MyView)v
? If so, how to do it ? Should I define a sub-interface ?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你可以使用:
这样你就知道你正在正确的视图上操作 - 如果给你错误类型的视图,它会抛出异常。 (如果您不想引发异常,可以使用
instanceof
首先测试它是否是正确的视图类型。)Well, you could use:
That way you know you're operating on the right view - and it will throw an exception if you are given the wrong kind of view. (If you don't want to throw an exception, you could use
instanceof
to test that it's the right kind of view first.)