1. 程式人生 > >DialogFragment實現自定義佈局的小技巧

DialogFragment實現自定義佈局的小技巧

DialogFragment可以說是用起來很方便,也很容易上手的一個類了,上次部落格寫了一篇關於將DatePicker放入DialogFragment中的文章,之後又遇到了將一整個佈局放入DialogFragment中的情況,寫著來記錄一下

一般來說,我們在DialogFragment中放入一個View只需要像這樣寫

View v = LayoutInflater.from(getActivity().getApplication())
                .inflate(R.layout.datepicker, null);

但是如果我們需要把一整個佈局都傳入,而且還需要獲得佈局內控制元件的引用時,我們就需要一個ViewGroup傳入,那這怎麼才能在DialogFragment中實現呢?其實還是很簡單的,只需要在onCreateView函式中將ViewGroup取出就可以了,具體程式碼如下:

 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,@Nullable Bundle savedInstanceState) {
        mViewGroup = container;
        return super.onCreateView(inflater, container, savedInstanceState);
    }

然後再使用提取出的mViewGroup來獲得整個佈局

@NonNull
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = LayoutInflater.from(getContext()) .inflate(R.layout.location_dialog_fragment, mViewGroup, false); ...... }

這樣就能輕鬆把自己寫的佈局再DialogFragment中展示了,獲得佈局中的控制元件就輕而易舉了

 mEditLocation = (Button) view.findViewById
(R.id.edit_location); mThingStatement=(EditText)view.findViewById(R.id.thing_statement); mSpendMoney = (EditText) view.findViewById(R.id.spend_money); mStartTime = (TextView) view.findViewById(R.id.start_time); mSpendTime = (EditText) view.findViewById(R.id.spend_time);
以上,如有錯誤,懇請指出