在android中访问重写方法的参数的子方法?

发布于 2024-10-03 14:41:03 字数 843 浏览 8 评论 0原文

这一定是一个菜鸟问题,但我找不到适当的等待来实现以下目标:

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧伤慢歌 2024-10-10 14:41:03

好吧,你可以使用:

public boolean onClick(View v) {
    MyView mv = (MyView) v;
    mv.myMethod();
}

这样你就知道你正在正确的视图上操作 - 如果给你错误类型的视图,它会抛出异常。 (如果您不想引发异常,可以使用 instanceof 首先测试它是否是正确的视图类型。)

Well, you could use:

public boolean onClick(View v) {
    MyView mv = (MyView) v;
    mv.myMethod();
}

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文