里面OnClickListener我无法访问很多东西 - 如何处理?很多东西、如何处理、无法访问、里面

2023-09-12 10:56:22 作者:烟祭

里面的OnClickListener我无法访问大多数变量外的范围,像这样的:

Inside an OnClickListener I cannot access most variables "outside" of the scope, like this:

findViewById(R.id.Button01).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent mainApps = new Intent(Intent.ACTION_MAIN);
                mainApps.addCategory(Intent.CATEGORY_LAUNCHER);
                List<ActivityInfo> activities = this.getPackageManager().queryIntentActivities(mainApps, 0);
                /*
                Intent intent = new Intent("com.sygic.drive/com.sygic/drive/.SygicDriveActivity");
                startActivity(intent);*/
            }

        });

在这个例子中,我需要获得PacketManager,我不能得到它,因为我没有可用的OnClickListener内的语境。

in this example I need to get the PacketManager, and I cannot get it since I do not have the Context available inside the OnClickListener.

我可以做一个静态引用外部,内部使用它,但是是正确的?似乎很奇怪,要做到这一点所有的时间?

I could make a static reference outside, and use it inside, but is that correct? Seems odd to have to do that all the time?

推荐答案

替换在code与 MyActivity.this 其中MyActivity是你的Activity子类的类名。

Replace this in your code with MyActivity.this where MyActivity is the class name of your Activity subclass.

说明:当你使用这部分的code您正在创建一个匿名内部类: 新OnClickListener(){ 匿名内部类有一个参考,他们在创建类的实例。它看起来像你的一个活动子类中,创建它,因为findViewById是一种活动方式。活动的是一个语境,因此,所有你需要做的就是使用引用它,你将自动拥有。

Explanation: You are creating an anonymous inner class when you use this part of your code: new OnClickListener() { Anonymous inner classes have a reference to the instance of the class they are created in. It looks like you are creating it inside an Activity subclass because findViewById is an Activity method. Activity's are a Context, so all you need to do is use the reference to it that you have automatically.