Android之DialogFragment_android.support.v4.app.dialogfragment-程序员宅基地

技术标签: android studio  

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

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

AlertDialog	alertDialog = new AlertDialog.Builder(getActivity())
				.setMessage("需要开启网络,强烈建议开启GPS,是否开启?")
				.setPositiveButton("开启", new DialogInterface.OnClickListener() {
					@Override
					public 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.html
public 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;
	}

	@Override
	public 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);//设置样式
	}

	@Override
	public 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 {

	@Override
	protected 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();
	}
	@Override
	public 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();
    }
}




版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/I_do_can/article/details/51704953

智能推荐

error: command 'gcc' failed with exit status 1错误解决_pip3 install readline失败error: command 'gcc' failed-程序员宅基地

文章浏览阅读2.8k次。今天pip install 安装包出一下错误:creating build/temp.macosx-10.6-x86_64-2.7/saslgcc -fno-strict-aliasing -I/Users/zhangyan/miniconda2/envs/ikang/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-pro..._pip3 install readline失败error: command 'gcc' failed with exit status 1

mac终端查看IP信息_sszxr-程序员宅基地

文章浏览阅读1.1w次。打开shell输入命令:curl ip.gssszxr:~ sszxr$ curl ip.gsCurrent IP / 当前 IP: 58.66.12.28ISP / 运营商: ChinaTelecomCity / 城市: Guangzhou GuangdongCountry / 国家: ChinaIP.GS is now IP.SB, please visit https://i..._sszxr

实现我们的数据库访问 ASP.NET 里面的DBHelper 工具类的编写_asp web dbhelper不统一-程序员宅基地

文章浏览阅读599次。实现我们的ASP.NET 的DBHelper类的使用配置文件处理了 <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Leave..._asp web dbhelper不统一

Oracle数据库启动之最恶心的报错检查--ORA-00119、ORA-00130-程序员宅基地

文章浏览阅读194次。今天一同事告知,新clone的数据库无法正常启动,登陆启动之后报错如下:[oracle@PlanDB01Dev ~]$ sqlplus / as sysdbaSQL*Plus: Release 11.2.0...._connected to an idle instance disconnected

黑客登录界面科幻黑色主题网页模板表单验证代码_黑客页面-程序员宅基地

文章浏览阅读3.3k次,点赞2次,收藏11次。黑客登录界面科幻黑色主题网页模板表单验证代码效果:html代码:<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> <style type="text/css"> label { cursor: pointer; color: white; } * {_黑客页面

SSDA-YOLO:新的YOLOv5改进方法——用于跨域目标检测的半监督域自适应YOLO方法-程序员宅基地

文章浏览阅读3.8k次,点赞6次,收藏54次。域自适应目标检测(DAOD)旨在缓解跨域差异导致的传输性能下降。然而,大多数现有的DAOD方法由计算密集的两级检测器主导,这不是工业应用的首选。本文提出了一种新的基于半监督域自适应YOLO(SSDA-YOLO)的方法,通过将紧凑型单级检测器YOLOv5与域自适应相结合来提高跨域检测性能。_ssda-yolo

随便推点

KCF源码下载-程序员宅基地

文章浏览阅读397次,点赞3次,收藏6次。刚接触CV领域,想在MATLAB上跑一下KCF算法,还特意在csdn下载了一个C++代码,又是配VS又是配OpenCV,不好用…直接链接KCF作者网页链接下滑找到KCF文章论文pdf、MATLAB代码、C++代码全在_kcf源码

对抗样本之DeepFool原理&coding-程序员宅基地

文章浏览阅读3.3k次,点赞4次,收藏38次。目录1 笔者言2 coding2.1 训练模型2.2 DeepFool对抗样本生成2.3 测试鲁棒性2.4 可视化展示附录1 笔者言虽说标题有DeepFool原理,但能力有限,这个我确实讲不清楚。与FGSM,BIM,MIM,CW等生成对抗样本的方法相比,deepfool是最难的了。给你推荐一个我看懂了的文章,但切记,想要真正明白deepfool的原理,就一定要耐下性子认真看,还要多动笔画示意图。言至此,传送门本文主要讲解代码,完成生成deepfool对抗样本的完整过程。直接复制代码就能跑。相信我,不_deepfool

java pdf写入中文时不显示,如何解决。_basefont.createfont("stsongstd-light","unigb-ucs2--程序员宅基地

文章浏览阅读1.6w次。java中生成pdf文件需要用到java文件:iText 5.0.6.jar文件只下载iText5.0.6.jar文件是不能写入中文到pdf文件,同时需要iTextAsian.jar但是我们在使用这2个jar文件的时候仍然发现一个问题,只能设置windos自带的文字库才能把中文写入: 例子:BaseFont baseFont = BaseFont.createFont("_basefont.createfont("stsongstd-light","unigb-ucs2-h", false)

Linux C语言内联汇编-函数调用_g++ 内嵌汇编 call-程序员宅基地

文章浏览阅读875次。int func(int a, int b, int c, int d, int e, int x, int y, int z){ return 1;}int main() { res = func(1, 2, 3, 4, 5, 6, 7, 8); cout &lt;&lt; res; return 0;}g++ -S查看汇编subq $16,..._g++ 内嵌汇编 call

【自动化测试】——robotframework实战(一)搭建环境_using legacy 'setup.py install' for wxpython, sinc-程序员宅基地

文章浏览阅读833次。python自动化测试框架robotframework的下载与安装_using legacy 'setup.py install' for wxpython, since package 'wheel' is not i

java.lang.NoClassDefFoundError: org/apache/jsp/licence_jsp (wrong name: org/apac-程序员宅基地

文章浏览阅读209次。java.lang.NoClassDefFoundError: org/apache/jsp/licence_jsp (wrong name: org/apache/jsp/Licence_jsp)javax.servlet.ServletException: org/apache/jsp/licence_jsp (wrong name: org/apache/jsp/Lice..._java.lang.noclassdeffounderror: org/apache/jsp/accountsettings_jsp (wrong na