在Java中,如何在新的侦听器块中访问静态方法参数? [英] In Java, how can I access static method parameters inside a new listener block?

查看:108
本文介绍了在Java中,如何在新的侦听器块中访问静态方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受两个参数的静态方法.在方法内部,我正在创建一个新对象并将新的侦听器附加到该对象.问题在于,侦听器块需要访问外部静态方法变量,但我不知道如何引用它们.我知道如何使用非静态方法来实现此目的,而不是使用静态方法.

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.

这是代码:

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;
            }
        });

被星号包围的上下文和意图变量是传递给静态方法的对象.由于OnTouchListener是一个内部块,因此它不知道那些对象.我该如何引用它们?

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?

推荐答案

在创建侦听器之前,将静态方法的参数声明为final,或者将传递的参数分配给static方法中的final局部变量.您可以从匿名类定义中使用最终引用.

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.

这篇关于在Java中,如何在新的侦听器块中访问静态方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆