简体   繁体   中英

Should I use “_activity = this;”?

Should I use " _activity = this; "?

I've seen _activity referenced many times in sample code. So, I arbitrarily decided that it looked like a good practice and have been using in all my code for awhile (over a year). But, before I start spreading the word around more I wanted to find some proper documentation that using a global (activity-local) context variable is good practice or not.

Anybody have ideas/thoughts/links? Know of any pros and cons?

One resource that I have found so far seems to say there are good and bad times to use this

I know that I could use this or MainActivity.this , but that's not the question.

..Just in case you don't know what I'm talking about, here is a trvial example made up on the spot:

public class MainActivity extends Activity {
    MainActivity _activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        _activity = this; // TODO: Find out if this is good practice?
        setContentView(R.layout.activity_main);
    }

    public void onClickButton(View v) {
        Toast.makeText(_activity, "Five boxing wizards", Toast.LENGTH_LONG).show();

        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(_activity, "asdf", Toast.LENGTH_LONG).show();
            }
        });
    }
}

EDIT: Another side-question for the comments: By a show of hands, who actually uses _activity ?

This is not good practice. Simply use this in most cases, and MainActivity.this when creating an anonymous subclass, etc.

I think the right question to ask yourself is, "does adding this member variable do anything for me", or "is there anything I can do with _activity that I can't do with this . I can tell you the answer is "no", but you should decide for yourself whether it is true.

It is not good practice.

Apart from not achieving anything (that can't be done by using this directly):

  • it makes the parent object bigger (by one reference),
  • it is potentially a bit slower, and
  • it makes your code more fragile; eg if someone accidentally assigns a different value to the variable.

I would argue that the code is less readable, but you might not agree with that.

No, it's not good. If I'm reading code I know what "this" means but if I see that I need to investigate.

That only makes sense when your outer class is not an activity, but you need one. For example, if you wanted too define your onclicklistener in its own file, you would need to pass in and store a reference (and be careful not too leak as note ;)

除了创建不必要的引用(因为实例也可以通过this关键字或MainActivity.this根据Java编程语言代码约定,也不建议使用带下划线的字段名:9.命名约定

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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