What's the difference between the various methods to get a Context?

前端 未结 8 684
情书的邮戳
情书的邮戳 2020-11-22 04:06

In various bits of Android code I\'ve seen:

 public class MyActivity extends Activity {
    public void method() {
       mContext = this;    // since Activi         


        
8条回答
  •  甜味超标
    2020-11-22 05:10

    I read this thread a few days ago, asking myself the same question. My decision after reading this was simple: always use applicationContext.

    However, I encountered a problem with this, I spent a few hours to find it, and a few seconds to solve it... (changing one word...)

    I am using a LayoutInflater to inflate a view containing a Spinner.

    So here are two possibilities:

    1)

        LayoutInflater layoutInflater = LayoutInflater.from(this.getApplicationContext());
    

    2)

        LayoutInflater layoutInflater = LayoutInflater.from(this.getBaseContext());
    

    Then, I am doing something like this:

        // managing views part
        View view = ContactViewer.mLayoutInflater.inflate(R.layout.aViewContainingASpinner, theParentView, false);
        Spinner spinner = (Spinner) view.findViewById(R.id.theSpinnerId);
        String[] myStringArray = new String[] {"sweet","love"};
    
        // managing adapter part
        // The context used here don't have any importance -- both work.
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this.getApplicationContext(), myStringArray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    
        theParentView.addView(view);
    

    What I noticed: If you instantiated your linearLayout with the applicationContext, then when you click on the spinner in your activity, you will have an uncaught exception, coming from the dalvik virtual machine (not from your code, that's why I have spent a lot of time to find where was my mistake...).

    If you use the baseContext, then that's all right, the context menu will open and you will be able to choose among your choices.

    So here is my conclusion: I suppose (I have not tested it further) than the baseContext is required when dealing with contextMenu in your Activity...

    The test has been done coding with API 8, and tested on an HTC Desire, android 2.3.3.

    I hope my comment have not bored you so far, and wish you all the best. Happy coding ;-)

提交回复
热议问题