Fragment inner class should be static

后端 未结 5 2110
说谎
说谎 2020-11-29 20:47

I have a FragmentActivity class with inner class that should display Dialog. But I am required to make it static. Eclipse offers me to

5条回答
  •  无人及你
    2020-11-29 21:19

    I won't talk about inner fragments, but more specifically about a DialogFragment defined within an activity because it's 99% of the case for this question.
    From my point of view, I don't want my DialogFragment (your NetworkConnectionError) to be static because I want to be able to call variables or methods from my containing class (Activity) in it.
    It won't be static, but I don't want to generate memoryLeaks either.
    What is the solution?
    Simple. When you go in onStop, ensure you kill your DialogFragment. It's as simple as that. The code looks like something like that:

    public class CarActivity extends AppCompatActivity{
    
    /**
     * The DialogFragment networkConnectionErrorDialog 
     */
    private NetworkConnectionError  networkConnectionErrorDialog ;
    //...  your code ...//
    @Override
    protected void onStop() {
        super.onStop();
        //invalidate the DialogFragment to avoid stupid memory leak
        if (networkConnectionErrorDialog != null) {
            if (networkConnectionErrorDialog .isVisible()) {
                networkConnectionErrorDialog .dismiss();
            }
            networkConnectionErrorDialog = null;
        }
    }
    /**
     * The method called to display your dialogFragment
     */
    private void onDeleteCurrentCity(){
        FragmentManager fm = getSupportFragmentManager();
         networkConnectionErrorDialog =(DeleteAlert)fm.findFragmentByTag("networkError");
        if(networkConnectionErrorDialog ==null){
            networkConnectionErrorDialog =new DeleteAlert();
        }
        networkConnectionErrorDialog .show(getSupportFragmentManager(), "networkError");
    }
    

    And that way you avoid memory leaks (because it's bad) and you insure you don't have a [expletive] static fragment that cannot access your activity's fields and methods. This is the good way to handle that problem, from my point of view.

提交回复
热议问题