简体   繁体   English

我如何从匿名课程访问我的主课程?

[英]How am I accessing my main class from an anonymous class?

I thought I had a good grasp of what I was doing but whenever I feel like I have a good handle on something, I'm proven wrong :) 我以为我很清楚自己在做什么,但每当我觉得自己能够很好地掌握某些东西时,我就证明错了:)

The code in question is this 有问题的代码就是这个

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);




mButton = (Button)findViewById(R.id.m_button);
mButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
        }
    });

    }

My confusion is in the new Intent() and startActivity method. 我的困惑在于new Intent()startActivity方法。

I was under the assumption that as long as we're working inside an anonymous class View.OnClickListener that I'd have to do something like MainActivity.this.startActivity(intent); 我假设只要我们在一个匿名类View.OnClickListener ,我就必须做一些像MainActivity.this.startActivity(intent);

When I'm not inside the anonymous class, I can simply do new Intent(this,SecondActivity.class); 当我不在匿名类中时,我可以简单地执行new Intent(this,SecondActivity.class);

Can someone explain why I am able to call the startActivity(); 有人可以解释为什么我能够调用startActivity(); method but can't just use this in the intent parameter? 方法,但不能只在intent参数中使用this

In the case of the anonymous inner class this is the anonymous class itself. 在匿名内部类的情况下, this是匿名类本身。 To access the outer class this from the anonymous one you need to do OuterClassName.this . 要访问外部类this从一个匿名你需要做的OuterClassName.this

However an inner class is allowed to access variables and methods from the outer class. 但是,允许内部类从外部类访问变量和方法。 Whether the inner class is anonymous or not makes no difference what-so-ever. 内部阶级是否是匿名的,无论如何都没有区别。

See: 看到:

I thought inner classes could access the outer class variables/methods? 我以为内部类可以访问外部类变量/方法?

Java nested inner class access outer class variables Java嵌套内部类访问外部类变量

This is one of the most important differences between static and non-static inner classes. 这是静态和非静态内部类之间最重要的差异之一。

You only need the class name if (for example) you have a method with the same name in both classes so it call tell which one you mean. 如果(例如)你在两个类中都有一个具有相同名称的方法,那么你只需要类名,这样它就可以告诉你的意思。 That's what is happening with this , both the inner and outer class have a this - so it defaults to the inner one unless you say otherwise. 这就是与发生this ,内和外班有this -所以它默认为内部一个,除非你说,否则。

From your inner class you can use new Intent(MainActivity.this, AnotherActivity.class) 从内部类中,您可以使用新的Intent(MainActivity.this, AnotherActivity.class)

Because it's a this of your outer activity, not the inner class' this 因为它是一个this的外活动,而不是内部类的this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM