承接上一节,本节说一下Fragment的子类,继承关系如下图


Fragment初学3——使用Fragment的子类DialogFragment_xml



Fragment有四个子类 ,就按顺序来吧,因为篇幅太长,我就一篇说一个




DialogFragment,顾名思义,就是用Fragment方式实现Dialog的效果,使用DialogFragment至少需要实现onCreateView或者onCreateDialog方法。onCreateView即使用定义的 xml布局文件展示Dialog。onCreateDialog即利用AlertDialog或者Dialog创建出Dialog


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_width="wrap_content"
         android:layout_height="wrap_content"
         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。