Wednesday, 14 May 2014

Example of dialog fragment with listview (coded)

Here is short example how create dialog fragment with list in code.

 public class DialogMyListFragment extends DialogFragment {  
   
   private android.widget.AdapterView.OnItemClickListener onItemClickListener;  
   private Core application;  
   public static String TAG = "DialogMyListFragment";  
   
   public static DialogMyListFragment getInstance() {  
     DialogMyListFragment df = new DialogMyListFragment();  
     return df;  
   }  
   
   public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {  
     this.onItemClickListener = onItemClickListener;  
   }  
   
   @Override  
   public Dialog onCreateDialog(Bundle savedInstanceState) {  
   
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());  
     ListView list = new ListView(getActivity());  
   
     application = (Core) getActivity().getApplication();  
   
     List<String> elements = new ArrayList<String>();  
           for(int i=0;i<10;i++)  
                elements.add("item " + i);  
             
     ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, elements);  
       
           list.setAdapter(adapter);  
     list.setOnItemClickListener(onItemClickListener);  
   
     builder.setView(list);  
   
     return builder.create();  
   
   }  
   
 }  

And then you call

 DialogMyListFragment df = new DialogMyListFragment().getInstance();  
 df.setOnItemClickListener(listener); 
 Fragment fr = getSupportFragmentManager().findFragmentByTag(DialogMyListFragment.TAG);  
 if (fr == null) {  
      df.show(getSupportFragmentManager(), DialogMyListFragment.TAG);  
 }