开发者

Accessing a submethod of an argument of an overriden method in android?

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!


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜