2011-12-25 39 views

回答

1

在我的片段類中寫了ShowDialog(int id)和removeDialog(int id)。

protected void showDialog(int id) { 

     AlertDialog dialog = null; 
      switch (id) { 
      case SHOWERROR_ID: 
       dialog = new AlertDialog.Builder(mActivity) 
         .setTitle(getString(R.string.alert)) 
         .setIcon(R.drawable.error) 
         .setMessage(d_msg) 
         .setPositiveButton(getString(R.string.ok), 
         new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog,int whichButton) { 
             removeDialog(SHOWERROR_ID); 
         } 
         }) 
         .setNegativeButton(null, 
           new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, 
              int whichButton) { 
            } 
         }).create(); 
       break; 
      default: 
       break; 
      } 

      if (dialog != null) { 
       FragmentManager fm = getActivity().getSupportFragmentManager(); 
       FragmentTransaction ftr = fm.beginTransaction(); 

       CustomDialogFragment newFragment = CustomDialogFragment 
         .newInstance(dialog); 

       DialogFragment fragmentDialog = (DialogFragment) fm 
         .findFragmentByTag("" + id); 

       if (fragmentDialog != null) { 
        ftr.remove(fragmentDialog); 
        ftr.commit(); 

       } 
       newFragment.show(fm, "" + id); 
      } 
     } 

    protected void removeDialog(int pDialogId) { 
      FragmentManager fm = getActivity().getSupportFragmentManager(); 
      FragmentTransaction ftr = fm.beginTransaction(); 
      DialogFragment fragmentDialog = null; 

      fragmentDialog = (DialogFragment) fm.findFragmentByTag("" + pDialogId); 

      if (fragmentDialog != null) { 
       FragmentTransaction f = ftr.remove(fragmentDialog); 
       f.commit(); 
      } 
    } 

    protected static class CustomDialogFragment extends DialogFragment { 
      private Dialog mDialog; 

      public static CustomDialogFragment newInstance(Dialog dialog) { 
       CustomDialogFragment frag = new CustomDialogFragment(); 
       frag.mDialog = dialog; 
       return frag; 
      } 

      public Dialog onCreateDialog(Bundle savedInstanceState) { 
       return mDialog; 
      } 
    }