Android入门教程 | DialogFragment 的使用

弹窗,是常见的一种提示方式。

DialogFragment是在3.0时引入的,是一种特殊的 Fragment,用于在 Activity 上展示一个模态的对话框。

DialogFragment 示例

确定UI样式

首先我们得知道做成什么样。一般来说简单的弹窗是一个标题,一端文字内容。 或者带有一两个按钮。

这里我们做一个有标题和文字的简单弹窗。

layout

确定好样式后,先把 layout 写出来。

dialog_simple.xml


    
    
新建弹窗类

新建一个 SimpleDialog类继承 DialogFragment

  • onCreate方法中接收传入的数据。传递数据使用了Bundle。
  • onCreateView方法中,使用上文建立的layout。
  • onViewCreated方法中进行ui操作。

    import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.DialogFragment;public class SimpleDialog extends DialogFragment {public static final String K_TITLE = "k_title"; // 传输数据时用到的keypublic static final String K_CONTENT = "k_content";private String title;private String content;@Overridepublic void onCreate(@Nullable Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    Bundle in = getArguments();    if (in != null) {
            title = in.getString(K_TITLE);
            content = in.getString(K_CONTENT);
        }
    }@Nullable@Overridepublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    return inflater.inflate(R.layout.dialog_simple, container, false);
    }@Overridepublic void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {    super.onViewCreated(view, savedInstanceState);    TextView titleTv = view.findViewById(R.id.title_tv);    TextView contentTv = view.findViewById(R.id.content_tv);
        titleTv.setText(title);
        contentTv.setText(content);
    }
    }
使用

把这个窗口弹出来。我们使用 DialogFragment.show(@NonNull FragmentManager manager, @Nullable String tag)方法。

private void popSimpleDialog1(String title, String content) {
        SimpleDialog dialog = new SimpleDialog();
        Bundle bundle = new Bundle();
        bundle.putString(SimpleDialog.K_TITLE, title);
        bundle.putString(SimpleDialog.K_CONTENT, content);
        dialog.setArguments(bundle);
        dialog.show(getSupportFragmentManager(), "one-tag");
    }    // 调用
    popSimpleDialog1("欢迎访问");

运行到机器上可以看到效果。

小结:
使用 DialogFragment 来实现弹窗。 需要确定 ui 样式,建立 layout,新建类继承DialogFragment,传入数据。

Android零基础入门教程视频参考


请使用浏览器的分享功能分享到微信等