How To Avoid Static Context Reference When I Need To Use A Activity Context?
After read this topic avoiding memory leaks some doubts arouse. If I need to use an activity context (example: inflate a view in a PopupWindow class to show a popup) how can I hold
Solution 1:
Working from the code you linked in the comments, why not do this:
//my main activitypublicclassExampleStaticReferenceActivityextendsActivity {
//...publicvoidmethodCalledWhenUserPressesButton(){
LinearLayoutmasterLayout= (LinearLayout) findViewById(R.id.masterLayout);
//now passing a reference to the current activity - elevine
masterLayout.addView(ButtonCreator.createButton(this));
}
}
//this class is in another packagepublicclassButtonCreator {
//added a Context parameter - elevinepublicstatic Button createButton(Context context) {
Button button;
button = newButton(context);
//... some configurations for buttonreturn button;
}
}
Solution 2:
That will crash your Application since Your Activity will be killed by OS when it runs out of Resources thus Context will also be null.. And its meaningless to give A background Activities Instance when you want to show pop up in the Foreground Activity.. What the Blog says is avoid passing activity.this where even getApplicationContext() can do the job..
Post a Comment for "How To Avoid Static Context Reference When I Need To Use A Activity Context?"