Android之DialogFragment

来源:互联网 发布:java异步日志系统 编辑:程序博客网 时间:2024/06/09 13:55

本文只是记录一些零碎的东西

开发中弹窗是使用很频繁的一个类,一般使用AlertDialog 如下

AlertDialogalertDialog = new AlertDialog.Builder(getActivity()).setMessage("需要开启网络,强烈建议开启GPS,是否开启?").setPositiveButton("开启", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {// 转到手机设置界面startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);}}).setNegativeButton("取消", null).create();

google 早就提供了DialogFragment,今天过来学习下 

API : https://developer.android.com/reference/android/support/v4/app/DialogFragment.html

看一下API ,就会发现其实就是一个Fragment,用法没有任何改变,通过自定义,可以自定义出ConfirmDialogFragment,ProgressDialogFragment等等,看我小试牛刀



有和Fragment基本一致的生命周期,因此便于Activity更好的控制管理DialogFragment。 随屏幕旋转(横竖屏幕切换)DialogFragment对话框随之自动调整对话框大小。而AlertDialog和PopupWindow随屏幕切换而消失。 DialogFragment的出现解决 横竖屏幕切换Dialog消失的问题。

看看MyDialogFragment代码,有Dialog回传值

import android.annotation.SuppressLint;import android.os.Bundle;import android.support.v4.app.DialogFragment;import android.text.TextUtils;import android.view.LayoutInflater;import android.view.View;import android.view.View.OnClickListener;import android.view.ViewGroup;import android.view.Window;import android.widget.EditText;import android.widget.TextView;// https://developer.android.com/reference/android/app/DialogFragment.htmlpublic class MyDialogFragment extends DialogFragment {int mNum = 0;private EditText editText;private MainActivity ac;/** * 通过newInstance()创建实例,并返回,这里的处理和系统从save状态中re-create相同。 1、通过 显示的标题,信息,显示类型 * 构造函数创建对象 2、将传递的信息设置为fragment的参数 3、返回对象 */static MyDialogFragment newInstance(String title, String message, int style) {MyDialogFragment f = new MyDialogFragment();Bundle args = new Bundle();args.putString("alert_title", title);args.putString("alert_message", message);args.putInt("alert_style", style);f.setArguments(args);return f;}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mNum = getArguments().getInt("alert_style");int style = 0;switch (mNum) {case 0:style = DialogFragment.STYLE_NORMAL;// 默认样式break;case 1:style = DialogFragment.STYLE_NO_TITLE;// 无标题样式break;case 2:style = DialogFragment.STYLE_NO_FRAME;// 无边框样式break;case 3:style = DialogFragment.STYLE_NO_INPUT;// 不可输入,不可获得焦点样式break;}setStyle(style, 0);//设置样式}@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {getDialog().setTitle(getArguments().getString("alert_title"));//添加标题//        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题View view = inflater.inflate(R.layout.fragment_dialog, container, false);((TextView)view.findViewById(R.id.alert_message)).setText(getArguments().getString("alert_message") );editText = (EditText) view.findViewById(R.id.alert_input);ac = (MainActivity)getActivity();view.findViewById(R.id.alert_ok).setOnClickListener(new OnClickListener() {public void onClick(View v) {// When button is clicked, call up to owning activity.//((FragmentDialog) getActivity()).showDialog();if(!TextUtils.isEmpty(editText.getText())){ac.showDialogMessage(editText.getText().toString());}dismiss();}});view.findViewById(R.id.alert_cancle).setOnClickListener(new OnClickListener() {public void onClick(View v) {dismiss();}});return view;}}

布局文件fragment_dialog
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp"    android:orientation="vertical" >    <TextView        android:id="@+id/alert_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:gravity="center"        android:text="dialog fragment" />    <TextView        android:id="@+id/alert_message"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:gravity="center"        android:text="dialog fragment message"        android:textSize="20dp" />    <EditText        android:id="@+id/alert_input"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp"        android:inputType="text" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="5dp" >        <TextView            android:id="@+id/alert_ok"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:gravity="center"            android:text="确定" />        <TextView            android:id="@+id/alert_cancle"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:gravity="center"            android:text="取消" />    </LinearLayout></LinearLayout>
再看看怎么调用的

import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentTransaction;import android.util.Log;import android.view.Menu;import android.view.View;import android.widget.Toast;public class MainActivity extends FragmentActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void showDia(View view){// DialogFragment.show() will take care of adding the fragment    // in a transaction.  We also want to remove any currently showing    // dialog, so make our own transaction and take care of that here.    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();    Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");    if (prev != null) {        ft.remove(prev);        Log.i("slack", "prev != null");    }    ft.addToBackStack(null);    // Create and show the dialog.    MyDialogFragment newFragment = MyDialogFragment.newInstance("title","message",0);    newFragment.show(ft, "dialog");}public void showDialogMessage(String message){Toast.makeText(this,message, Toast.LENGTH_SHORT).show();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
使用这个,如果再封装一下,可以整个项目的弹窗都使用DialogFragment,官方API里还提供了AlertDialog的组合使用,直接看官方的源码
public static class MyAlertDialogFragment extends DialogFragment {    public static MyAlertDialogFragment newInstance(int title) {        MyAlertDialogFragment frag = new MyAlertDialogFragment();        Bundle args = new Bundle();        args.putInt("title", title);        frag.setArguments(args);        return frag;    }    @Override    public Dialog onCreateDialog(Bundle savedInstanceState) {        int title = getArguments().getInt("title");        return new AlertDialog.Builder(getActivity())                .setIcon(R.drawable.alert_dialog_icon)                .setTitle(title)                .setPositiveButton(R.string.alert_dialog_ok,                    new DialogInterface.OnClickListener() {                        public void onClick(DialogInterface dialog, int whichButton) {                            ((FragmentAlertDialog)getActivity()).doPositiveClick();                        }                    }                )                .setNegativeButton(R.string.alert_dialog_cancel,                    new DialogInterface.OnClickListener() {                        public void onClick(DialogInterface dialog, int whichButton) {                            ((FragmentAlertDialog)getActivity()).doNegativeClick();                        }                    }                )                .create();    }}




0 0
原创粉丝点击