ListFragment as DialogFragment

前端 未结 2 560
误落风尘
误落风尘 2021-01-25 05:19

Is it possible to show ListFragment as Dialog? Or there\'s no way and I should implement my own ListView, empty TextView and

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 06:08

    Another Option:

    Build Dialog Fragment:

    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;    
    
    public class ListDialogFragment extends DialogFragment {
    
        private OnListDialogItemSelect listener;
        private String title;
        private String[] list;
    
        public ListDialogFragment(OnListDialogItemSelect listener, String[] list, String title) {
            this.listener=listener;
            this.list=list;
            this.title=title;
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
    
            return new AlertDialog.Builder(getActivity())
                    .setTitle(title)
                    .setCancelable(false)
                    .setItems(list, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
    
                            listener.onListItemSelected(list[item]);
                            getDialog().dismiss(); 
                            ListDialogFragment.this.dismiss();
    
                        }
                    }).create();
    
        }
    
        public interface OnListDialogItemSelect{
            public void onListItemSelected(String selection);
        }
    
    }
    

    On Your Fragment Activity like this:

    public class YourActivity extends FragmentActivity implements OnListDialogItemSelect{
    
        private void showCountryFragment(){
             FragmentManager fm = getSupportFragmentManager();
             ListDialogFragment newFragment = new ListDialogFragment(this,getCountries(),"Country:");
             newFragment.show(fm, "country_picker");
        }
    
        @Override
        public void onListItemSelected(String selection) {
            _bt_country.setText(selection);
        }
    
    }
    

提交回复
热议问题