天天看點

Fragment初學3——使用Fragment的子類DialogFragment

承接上一節,本節說一下Fragment的子類,繼承關系如下圖

Fragment有四個子類,就按順序來吧,因為篇幅太長,我就一篇說一個

DialogFragment,顧名思義,就是用Fragment方式實作Dialog的效果,使用DialogFragment至少需要實作onCreateView或者onCreateDialog方法。onCreateView即使用定義的 xml布局檔案展示Dialog。onCreateDialog即利用AlertDialog或者Dialog建立出Dialog

1、onCreateView實作DialogFragment

MyDialogFragment的布局如下

<RelativeLayout xmlns:android="

http://schemas.android.com/apk/res/android

"

    android:id="@+id/edit_name"

    android:layout_width="match_parent"

    android:layout_height="match_parent" >

    <EditText

        android:id="@+id/editText_mydialog_fragment"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_marginLeft="16dp"

        android:layout_marginTop="116dp"

        android:layout_toRightOf="@+id/textView1"

        android:ems="10"

        android:imeOptions="actionDone"

        android:inputType="text" >

        <!-- imeOptions="actionDone"會将彈出的鍵盤上的enter按鈕顯示為完成(或Done) -->

        <requestFocus />

    </EditText>

    <TextView

        android:id="@+id/textView1"

        android:layout_alignBottom="@+id/editText_mydialog_fragment"

        android:layout_alignParentLeft="true"

        android:layout_marginLeft="28dp"

        android:text="名字"

        android:textSize="20sp" />

</RelativeLayout>

MyDialogFragment.java類

public class MyDialogFragment extends DialogFragment {

 private EditText mEditText;

 public MyDialogFragment() {

  // Empty constructor required for DialogFragment

 }

 @Override

 public View onCreateView(LayoutInflater inflater, ViewGroup container,

   Bundle savedInstanceState) {

  View view = inflater.inflate(R.layout.fragment_mydialog, container);

  mEditText = (EditText) view

    .findViewById(R.id.editText_mydialog_fragment);

  // getDialog().setTitle("Hello world");//設定标題

  getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标題

  mEditText.requestFocus(); // EditText獲得焦點

  getDialog().getWindow().setSoftInputMode(

    LayoutParams.SOFT_INPUT_STATE_VISIBLE); // 顯示軟鍵盤

  return view;

}

DialogFragment的顯示方法和普通Fragment還有點不一樣, 一般自定義Fragment,用FragmentManager.beginTransaction得到一個Transaction,然後調用相應 Transaction的方法(show,replace,attach、add),然後Transaction.commit(),展示 Fragment。而上面的MyDialogFragment則是用從DialogFragment繼承下來的show方法,通過參數傳入FragmentManager和Tag來展示的,這裡要注意一下。另外,預設情況下,回退鍵用來取消該dialog。

源碼

繼續閱讀