In Java, how can I access static method parameters inside a new listener block?

青春壹個敷衍的年華 提交于 2019-12-02 06:02:42

问题


I have a static method that accepts a couple of parameters. Inside the method I am creating a new object and attaching a new listener to it. The problem is that the listener block needs access to the outer static method variables, but I don't know how to reference them. I know how to make this happen with a non static method, but not with a static one.

Here is the code:

v.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_UP:             
                    ((Activity)*context*).startActivityForResult(*intent*, 0);
                    break;
                }

                return true;
            }
        });

The context and intent variables surrounded by the asterisks are objects passed into the static method. Since the OnTouchListener is an inner block, it is unaware of those objects. How can I reference them?


回答1:


Declare the parameters for the static method as final or assign the passed in arguments to final local variables in the static method before you create your listener. You can use the final references from inside the anonymous class definition.



来源:https://stackoverflow.com/questions/12237477/in-java-how-can-i-access-static-method-parameters-inside-a-new-listener-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!