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

本文详细介绍了如何使用Fragment子类DialogFragment来实现Dialog效果,包括自定义布局、展示方法及与普通Fragment的区别。同时,展示了DialogFragment的显示方法与普通Fragment的不同之处,以及如何在Fragment中使用DialogFragment。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

承接上一节,本节说一下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_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。


源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值