2013-03-17 5 views
19

es ist möglich, eine Kontextvariable an ein DialogFragment zu übergeben?Passender Kontext als Argument von DialogFragment

Ich habe diesen Code in Dialog verwenden, zum Durchführen eines string:

public static ConfirmDialog newInstance(String f) { 
    ConfirmDialog d = new ConfirmDialog(); 

    Bundle args = new Bundle(); 
    args.putString("FILE_NAME", f); 
    d.setArguments(args); 

    return d; 
} 

aber ich finde keine Funktion wie putString für Kontext übergeben. Es ist möglich, das zu tun?

Antwort

47

Ihre DialogFragment hat eine sehr praktische Methode für eine Context Instanz erhalten:

getActivity() 

Fragment#getActivity() wird die Instanz des Activity zurückkehren (das ist ein Context), dass die Fragment zu angebracht ist. Benutze es, nachdem das Fragment onAttach() aufgerufen wird. Die folgende Tabelle zeigt die Fragment lifecycle, wie Sie sehen können, unter Verwendung getActivity() von onCreate() bis onDestroy() sollte ein gültiger Anruf sein.

enter image description here

Weitere Informationen finden Sie in der Fragment Dokumentation

4
@Override 
public void onAttach(Activity activity) { 
    // TODO Auto-generated method stub 
    super.onAttach(activity); 
    context=activity; 
} 

Need Methode verwenden onAttach: für Dialog Fragment

+0

show() Methode erste und getActivity aufgerufen wird() ist null. Wie kann ich dann den Kontext bekommen? – ralphgabb

0

Verwendung wie folgt aus:

public class Dialog extends DialogFragment implements OnClickListener { 
    public void onClick(View v) { 
    switch (v.getId()) { 
     case R.id.message: { 
      this.startActivity(new Intent(context, Login.class)); 
           //or use getActivity() instead of context 
      } 
      break; 
     } 
    } 
    @Override 
    public void onAttach(Activity activity) { 
     // TODO Auto-generated method stub 
     super.onAttach(activity); 
     context=activity; 
    } 
} 
0

onAttach (Aktivität Aktivität) ist veraltet,

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
} 


Verwendung onAttach (Context Kontext) statt

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
}