DialogFragment

YH Lin
1 min readFeb 6, 2020

--

實作一個日曆型APP ,在日期中點擊後觸發對話的Fragment,紀錄對應事件後,將結果傳回 。大概類似這樣

先從layout 布局著手。一個 CalendarView 加上一個RecyclerView

回到Java 端來看。在onCreateView 中,先把 calendarView與recyclerview 加上來,並在calendarView設計 setOnDateChangeListener事件中觸發呼叫DialogFragment。呼叫DialogFragmnent 可以用show的方法呼叫

dialog = ConsultDialogFragment.newInstance(year,month,dayOfMonth);                dialog.show(getFragmentManager(),"dialog_fragment");            

但在DialogFragmnent 結束後,並不會返回onCreateView 更新RecyclerView 的結果,只好藉助callBack 方式,讓DialogFragment 的Button觸發後傳回Fragment 來呼叫。

DialogFragment 中加上一個interface,並為其設計事件NoticeDialogListener

public interface NoticeDialogListener {       
public void onDialogPositiveClick();
public void onDialogNegativeClick();
}

宣告一個變數 mListener

NoticeDialogListener mListener;

並在DialogFragment 的 onAttach 生命週期中給予mListener 初值

@Override    
public void onAttach(@NonNull Context context) {
super.onAttach(context);
getActivity().getApplication();
try {
mListener = (NoticeDialogListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException(e.toString()
+ " must implement NoticeDialogListener");
}
}

因為來源是從Fragment 呼叫DialogFragment的,所以mListener 的給值需要用 mListener = (NoticeDialogListener) getTargetFragment(); 同時來源端(Fragment )的onCreateView 的呼叫DialogFragment也需要調整為dialog.setTargetFragment(ConsultFragment.this,22);

dialog = ConsultDialogFragment.newInstance(year,month,dayOfMonth);                dialog.setTargetFragment(ConsultFragment.this,22);                dialog.show(getFragmentManager(),"dialog_fragment");

在DialogFragment 中設計了layout,因此在onCreateView 中需要載入,同時在save button 中的onClick執行 mListener.onDialogPositiveClick();

final View view = inflater.inflate(R.layout.fragment_consult_dialog,container,false);         save = view.findViewById(R.id.save_btn);        save.setOnClickListener(new View.OnClickListener() {
mListener.onDialogPositiveClick();
})

最後修改來源的Fragment 類別,實作NoticeDialogListener 介面的onDialogPositiveClick 方法,使其更新RecyclerView

public class ConsultFragment extends Fragment 
implements ConsultDialogFragment.NoticeDialogListener{

@Override
public void onDialogPositiveClick() {
datas = dao.getByDate(dd);
adpater = new ConsultAdapter(datas);
adpater.notifyDataSetChanged();
recyclerView.setAdapter(adpater);
}

}

完整的Fragment

完整的DialogFragment

--

--

No responses yet