如何选择在Java中获取相关上下文的正确方法?

huangapple go评论90阅读模式
英文:

How to choose the correct way to get relevant context in Java?

问题

我最近开始使用Java,正在尝试理解什么是“Context”,以及如何正确使用它。

public AdapterView.OnItemClickListener selectDevice = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        String info = ((TextView) view).getText().toString();
        String address = info.substring(info.length() - 17);
        Intent comIntent = new Intent(MainActivity.this, Communication.class); // 为什么要这样做???

    }
};

对于这个例子和Intent参数,为什么我们不使用“getContext()”或者“getApplicationContext”或者只是“this”呢?

英文:

I recently started using java and I'm trying to understand what exactly "Context" is, and how to use it properly.

public AdapterView.OnItemClickListener selectDevice = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int i, long l) {

            String info = ((TextView) view).getText().toString();
            String adress = info.substring(info.length()-17);
            Intent comIntent = new Intent(MainActivity.this, Communication.class); //WHY???


        }
    };

For this example and Intent arguement , why don't we use "getContext()" or "getApplicationContext" or just "this"?

答案1

得分: 1

调用 getContext() 或者 getApplicationContext() 和调用 this.getContext() 是一样的吗?this 返回的是你所在位置的对象类。因此,当你能够调用 getContext() 时,这意味着你在一个扩展了 Context 类并且有 getContext() 函数的类内部。例如,从 Activity 中你可以调用 getContext(),因为它具有这个函数。
但在这种情况下,你在 OnItemClickListener 类中。而那个类没有 getContext() 函数。你必须在一个具有 getContext() 函数的类内部。

英文:

Calling getContext() or getApplicationContext() is same as this.getContext() right? this gives an object class where you are in. So when you are able to call getContext() that means you are inside a class which extends Context class and has getContext() function.<br> For example from Activity you can call getContext() because it has the function.
But in this case you are in OnItemClickListener class. And that class has no function getContext(). You have to be in a class which has getContext() function.

答案2

得分: 1

我正在尝试理解什么是“上下文”。

为什么我们不使用“getContext()”或“getApplicationContext”,或者只使用“this”?

因为在匿名类中,this并不指代Activity。参见此处:

英文:

> I'm trying to understand what exactly "Context" is

https://stackoverflow.com/questions/3572463/what-is-context-on-android

> why don't we use "getContext()" or "getApplicationContext" or just
> "this"?

Because this does not refer to the Activity in anonymous classes.
See here
https://stackoverflow.com/questions/1084112/access-this-from-java-anonymous-class

huangapple
  • 本文由 发表于 2020年3月16日 19:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/60705154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定