Java – I should use “_activity = this;” Are you?
I should use "_activity = this;" Are you?
I see multiple references in the sample code_ activity. So I decided at random that it seemed like a good practice and had been used in all my code for some time (more than a year) However, before I begin to propagate the word, I want to find some appropriate documents. It is good practice to use global (active local) context variables
Does anyone have an idea / idea / link? Do you know any pros and cons?
So far, one resource I've found seems to indicate that there are good and bad times to use this
I know I can use this or mainactivity This, but it's not a problem
.. If you don't know what I'm talking about, here's a simple example:
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 @R_8_2419@ing wizards",Toast.LENGTH_LONG).show(); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(_activity,"asdf",Toast.LENGTH_LONG).show(); } }); } }
Editor: comment on another question: by raising your hand, who actually uses it_ activity?
Solution
It's not a good habit In most cases, you just need to use it and use mainactivity when creating anonymous subclasses This et al
I think the right question to ask myself is, "did adding this member variable do anything for me", or "what can I do with _activity? I can't do that. I can tell you the answer is" no ", but you should decide whether it's true or not