본문 바로가기

PROGRAMING/Android

interface를 이용하여 DialogFragment이벤트의 구현부를 다른 장소에 구현한다.

http://developer.android.com/guide/topics/ui/dialogs.html


interface를 정의 하여 DialogFragment를 호출한 쪽에서 이벤트 액션에 대한 내용을 구현하도록 한다.


DialogFragment


ublic class CheckBoxListAlertDialogFragment extends DialogFragment  {

//http://developer.android.com/guide/topics/ui/dialogs.html

    /* The activity that creates an instance of this dialog fragment must

     * implement this interface in order to receive event callbacks.

     * Each method passes the DialogFragment in case the host needs to query it. */

    public interface NoticeDialogListener {

       public void onDialogPositiveClick(DialogFragment dialog);

        public void onDialogNegativeClick(DialogFragment dialog);

        public LinkedHashMap<Long, AudioContent> getCheckBoxHashMap();

    }

    // Use this instance of the interface to deliver action events

    NoticeDialogListener mListener;



    @Override

    public void onAttach(Activity activity) {

        super.onAttach(activity);

        // Verify that the host activity implements the callback interface

        try {

            // Instantiate the NoticeDialogListener so we can send events to the host

            mListener = (NoticeDialogListener) getParentFragment();

        } catch (ClassCastException e) {

            // The activity doesn't implement the interface, throw exception

            throw new ClassCastException(activity.toString()+ " must implement NoticeDialogListener");

        }

    }



 public Dialog onCreateDialog(Bundle savedInstanceState) {

   

   

    ListView tmp  = (ListView)getActivity().getLayoutInflater().inflate(R.layout.alert_dialogfragment_checkbox_list,null);

    tmp.setAdapter(mCheckBoxArrayAdapter);

    int title = getArguments().getInt("title");

        return new AlertDialog.Builder(getActivity())

                .setTitle(title)

                .setView(tmp)

                .setPositiveButton(R.string.checkbox_list_alert_dialogfragment_ok,

                    new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {

                        LOG.i(CLASSNAME, "setPositiveButton onClick");               mListener.onDialogPositiveClick(CheckBoxListAlertDialogFragment.this);


TargetFragment


public class AudioMediaFragment extends Fragment implements

LoaderCallbacks<Cursor> , NoticeDialogListener{


~~~

@Override

public void onDialogPositiveClick(DialogFragment dialog) {

LOG.i(CLASSNAME, "onDialogPositiveClick dialog.getId() : "+ dialog.getId());

}

@Override

public void onDialogNegativeClick(DialogFragment dialog) {

LOG.i(CLASSNAME, "onDialogNegativeClick dialog.getId() : "+ dialog.getId());

}

@Override

public LinkedHashMap<Long, AudioContent> getCheckBoxHashMap() {

LOG.i(CLASSNAME, "getCheckBoxHashMap");

return mCheckBoxHasMap;

}



DialogFragment 뿐만 아니라 다른 곳에서도 응용할 수 있을 것 같다.