什么class_name.this这之间的不同不同、class_name、this

2023-09-07 14:58:26 作者:老师我晕课

我看到一些code使用 class_name.this 作为其上下文中的参数,有时使用直接在另一个演示code。我可以假设 class_name.this

I see some code use class_name.this as a parameter for its context, and sometimes use this directly in another demo code. May I assume that this is a abbreviation of class_name.this?

推荐答案

我们用如果类引用可以是类型强制转换为背景时。而当对象水湿是,然后我们用 ClassName.this (但只有当类是儿童/超级子[的子类的] Context类的。像活动/服务)

We use this when if the class references can be type-casted to Context. And when this object cann't be, then we use ClassName.this (BUT only if the class is child/ super child [subclass] of Context class. like Activity/ Services)

阅读什么是语境中的Andr​​oid?

让我通过例如code解释(比如我使用活动的AsyncTask

Let me explain by example code (For example I am using Activity and AsyncTask)

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.startActivity(intent); 
        // or 
        MainActivity.this.startActivity(intent); 
        // Both are same here. 
    }

    private class TestTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            this.startActivity(intent); // You can not do. Because "this" is the current object of AsyncTask not of Activity. 
            // So you can only use
            MainActivity.this.startActivity(intent); 
        }
    }
}