In Java, how can I access static method parameters

2019-02-27 01:41发布

问题:

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.