DialogFragment : Using AlertDialog with custom layout

后端 未结 2 1868
挽巷
挽巷 2020-12-13 09:44

I\'m rewriting my application with Fragments API support. In the original application I have an AlertDialog that is created like this :

<         


        
相关标签:
2条回答
  • 2020-12-13 10:44

    I'm surprised that nobody answered. This is the solution:

    public class PropDialogFragment extends DialogFragment {
    
        private PropDialogFragment() { /*empty*/ } 
    
        /** creates a new instance of PropDialogFragment */
        public static PropDialogFragment newInstance() {
            return new PropDialogFragment();
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            //getting proper access to LayoutInflater is the trick. getLayoutInflater is a                   //Function
            LayoutInflater inflater = getActivity().getLayoutInflater();
    
            View view = inflater.inflate(R.layout.my_dialog, null);
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setView(view);
            builder.setTitle(getActivity().getString(R.string.sysinfo)).setNeutralButton(
                    getActivity().getString(R.string.okay), null);
            return builder.create();
        }
    }
    

    You can show the dialog using :

    private void showDialog() {
        // DialogFragment.show() will take care of adding the fragment
        // in a transaction.  We also want to remove any currently showing
        // dialog, so make our own transaction and take care of that here.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
    
        // Create and show the dialog.
        DialogFragment newFragment = PropDialogFragment.newInstance();
        newFragment.show(ft, "dialog");
    }
    
    0 讨论(0)
  • 2020-12-13 10:47

    Basically you can just show your Fragment like this:

    SherlockDialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getActivity().getSupportFragmentManager(), "timePicker");
    

    And this would be a simple TimePickerFragment:

    public class TimePickerFragment extends SherlockDialogFragment implements TimePickerDialog.OnTimeSetListener{
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
    
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
    
    
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
    }
    
    0 讨论(0)
提交回复
热议问题