Android 适应任何自定义样式 提示弹出框 Dialog 封装
Android开发中Dialog对话框的使用
Dialog是android开发过程中最常用到的组件之一,它包括以下几种类型:警告对话框:Alertialog进度对话框:ProgressDialog日期选择对话框:DatePickerDialog时间选择对话框:TimePickerDialog自定义对话框:从Dialog继承Dialog的创建方式有两种:一是直接new一个Dialog对象,然后调用Dialog对象的show和dismiss方法来控制对话框的显示和隐藏。
二是在Activity的onCreateDialog(int id)方法中创建Dialog对象并返回,然后调用Activty的showDialog(int id)和dismissDialog(int id)来显示和隐藏对话框。
区别在于通过第二种方式创建的对话框会继承Activity的属性,比如获得Activity的menu事件等。
使用AlertDialog可以创建普通对话框、带列表的对话框以及带单选按钮和多选按钮的对话框。
普通对话框效果如下:代码://创建builderAlertDialog.Builder builder = newAlertDialog.Builder(DialogSampleActivity.this);builder.setTitle("普通对话框") //标题.setIcon(R.drawable.ic_launcher) //icon.setCancelable(false) //不响应back按钮.setMessage("这是一个普通对话框") //对话框显示内容//设置按钮.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogSampleActivity.this, "点击了确定按钮", Toast.LENGTH_SHORT).show();}).setNeutralButton("中立", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogSampleActivity.this, "点击了中立按钮", Toast.LENGTH_SHORT).show();}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogSampleActivity.this, "点击了取消按钮", Toast.LENGTH_SHORT).show();});//创建Dialog对象AlertDialog dlg = builder.create();return dlg;带列表的对话框效果图:代码:final CharSequence[] items = { "Item1", "Item2", "Item3" };// 创建builderAlertDialog.Builder builder = new AlertDialog.Builder(DialogSampleActivity.this);builder.setTitle("列表对话框") // 标题.setIcon(R.drawable.ic_launcher) // icon.setCancelable(false) // 不响应back按钮.setItems(items, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogSampleActivity.this,"选择了" + items[which], Toast.LENGTH_SHORT).show();});// 创建Dialog对象AlertDialog dlg = builder.create();return dlg;带单选按钮的列表对话框只需将setItems替换为:.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogSampleActivity.this,"选择了" + items[which], Toast.LENGTH_SHORT).show();});这里多了一个参数-1,代表默认选中第几项,-1表示默认不选中带复选框的列表对话框只需将setItems替换为:.setMultiChoiceItems(items, checked, newDialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {Toast.makeText(DialogSampleActivity.this,"选择了" + items[which], Toast.LENGTH_SHORT).show();});参数checked伟boolean数组,表示默认哪些复选框是被选中的。
Android对话框(Dialog)大全建立你自己的对话框.
Android 对话框(Dialog大全建立你自己的对话框Activities提供了一种方便管理的创建、保存、回复的对话框机制,例如onCreateDialog(int, onPrepareDialog(int, Dialog, showDialog(int,dismissDialog(int等方法,如果使用这些方法的话,Activity将通过getOwnerActivity(方法返回该Activity管理的对话框(dialog.onCreateDialog(int:当你使用这个回调函数时,Android系统会有效的设置这个Activity为每个对话框的所有者,从而自动管理每个对话框的状态并挂靠到Activity上。
这样,每个对话框继承这个Activity的特定属性。
比如,当一个对话框打开时,菜单键显示为这个Activity定义的选项菜单,音量键修改Activity使用的音频流。
showDialog(int: 当你想要显示一个对话框时,调用showDialog(int id 方法并传递一个唯一标识这个对话框的整数。
当对话框第一次被请求时,Android 从你的Activity中调用onCreateDialog(int id,你应该在这里初始化这个对话框Dialog。
这个回调方法被传以和showDialog(int id相同的ID。
当你创建这个对话框后,在Activity的最后返回这个对象。
onPrepareDialog(int, Dialog:在对话框被显示之前,Android还调用了可选的回调函数onPrepareDialog(int id, Dialog. 如果你想在每一次对话框被打开时改变它的任何属性,你可以定义这个方法。
这个方法在每次打开对话框时被调用,而onCreateDialog(int 仅在对话框第一次打开时被调用。
如果你不定义onPrepareDialog(,那么这个对话框将保持和上次打开时一样。
Android常用的五种弹出对话框-电脑资料
Android常用的五种弹出对话框-电脑资料一个Android开发中常用对话框的小例子,共有五种对话框:普通弹出对话框,单选对话框,多选对话框,输入对话框及进度条样式对话框:xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" >android:id="@+id/common_dialog"android:layout_width="match_parent"android:layout_height="40dp"android:text="普通对话框"android:textSize="16sp"android:layout_marginTop="10dp" />android:id="@+id/radio_dialog"android:layout_width="match_parent"android:layout_height="40dp"android:text="单选对话框"android:textSize="16sp"android:layout_marginTop="10dp" />android:id="@+id/check_dialog"android:layout_width="match_parent"android:layout_height="40dp"android:text="多选对话框"android:textSize="16sp"android:layout_marginTop="10dp" />android:id="@+id/input_dialog"android:layout_width="match_parent"android:layout_height="40dp"android:text="输入文字对话框"android:textSize="16sp"android:layout_marginTop="10dp" /> android:id="@+id/progress_dialog"android:layout_width="match_parent" android:layout_height="40dp"android:text="进度条对话框"android:textSize="16sp"android:layout_marginTop="10dp" />下面是输入内容的简单布局activity_input.xmlxmlns:tools="/tools" android:id="@+id/LinearLayout1"android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" ><textview< p=""></textview<>android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /><edittext< p=""></edittext<>android:id="@+id/uname"android:layout_width="fill_parent"android:layout_height="wrap_content" /><textview< p=""></textview<>android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/hello_world" /><edittext< p=""></edittext<>android:id="@+id/upass"android:layout_width="fill_parent"android:layout_height="wrap_content" />代码及注释:public class MainActivity extends Activity implements OnClickListener {/**单选框模拟标题大学*/private final static int CHECKED_ENU = 0;/**单选框模拟标题高中*/private final static int CHECKED_SEL = 1;/**单选框模拟标题初中*/private final static int CHECKED_CHU = 2;/**复选按钮状态为全选 */private boolean[] checked = { true, true, true, false };/**模拟的进度值 */private int progressNumber;/**进度对话框 */private ProgressDialog progressDialog;/**对应按钮*/private Button commonBtn, radioBtn, checkBtn, inputBtn, progressBtn;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);initViews();initListeners();}/**初始化UI控件*/private void initViews() {monBtn = (Button) findViewById(mon_dialog);this.radioBtn = (Button) findViewById(R.id.radio_dialog);this.checkBtn = (Button) findViewById(R.id.check_dialog);this.inputBtn = (Button) findViewById(R.id.input_dialog);this.progressBtn = (Button) findViewById(R.id.progress_dialog);}/**注册按钮监听事件*/private void initListeners() {monBtn.setOnClickListener(this);this.radioBtn.setOnClickListener(this);this.checkBtn.setOnClickListener(this);this.inputBtn.setOnClickListener(this);this.progressBtn.setOnClickListener(this);}/**普通对话框 */private Dialog buildAlertDialog() {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.ic_launcher);builder.setTitle("对话框");builder.setMessage("您的密码不对!!");ImageView imageView = new ImageView(this);imageView.setImageResource(R.drawable.mm1);/**设置背景图片*/builder.setView(imageView);/**左边按钮*/builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是左边确定按钮!");}});/**中间按钮*/builder.setNeutralButton("详情", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是中间详情按钮!");}});/**右边按钮*/builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubsetTitle("您点击的是右边取消按钮!");}return builder.create();}/**单选按钮弹出框 */private Dialog buildAlertDialog_radio() {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.ic_launcher);builder.setTitle("对话框");/**单选按钮,默认高中被选中*/builder.setSingleChoiceItems(new String[] { "大学", "高中", "初中", "小学" }, 1, new DialogInterface.OnClickListener() { @Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubswitch (which) {case CHECKED_ENU:setTitle("大学");break;case CHECKED_SEL:setTitle("高中");break;case CHECKED_CHU:setTitle("初中");break;default:setTitle("小学");break;}}builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是左边确定按钮!");}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是右边取消按钮!");}});return builder.create();}/**可以多选按钮弹出框 */private Dialog buildAlertDialog_checkbox() {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.ic_launcher);builder.setTitle("对话框");/**复选按钮*/builder.setMultiChoiceItems(new String[] { "大学", "高中", "初中", "小学" }, checked, new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {setTitle("which=" + which + "-----" + "isChecked=" + isChecked);}});builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击了确定按钮!");}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubsetTitle("您点击的是了取消按钮!");}});return builder.create();}/**含可以输入文本的弹出框 */private Dialog buildAlertDialog_input() {AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setIcon(R.drawable.ic_launcher);builder.setTitle("对话框");LayoutInflater inflater = LayoutInflater.from(this);builder.setView(inflater.inflate(yout.activity_input, null));builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是确定按钮!");}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {setTitle("您点击的是取消按钮!");}});return builder.create();}/**进度对话框 */private Dialog buildAlertDialog_progress() {progressDialog = new ProgressDialog(this);progressDialog.setTitle("进度条");progressDialog.setMessage("正在下载...........");/**进度条样式 */progressDialog.setProgressStyle(ProgressDialog.STYLE_ HORIZONTAL);/**模糊效果 */progressDialog.setIndeterminate(false);return progressDialog;}/**每隔0.3秒更新一次进度 */public void updateProgress() {new Thread() {@Overridepublic void run() {try {while (progressNumber <= 100) { progressDialog.setProgress(progressNumber++); Thread.sleep(300);super.run();}/**下载完后,关闭下载框 */progressDialog.cancel();} catch (InterruptedException e) {e.printStackTrace();}}}.start();}@Overridepublic void onClick(View v) {switch (v.getId()) {case mon_dialog:buildAlertDialog().show();break;case R.id.radio_dialog:buildAlertDialog_radio().show();break;case R.id.check_dialog:buildAlertDialog_checkbox().show();break;case R.id.input_dialog:buildAlertDialog_input().show(); break;case R.id.progress_dialog: buildAlertDialog_progress().show(); updateProgress();break;default:break;}}}。
Android多种简单的弹出框样式设置代码
Android多种简单的弹出框样式设置代码简介这是⼀个基于AlertDialog和Dialog这两个类封装的多种弹出框样式,其中提供各种简单样式的弹出框使⽤说明。
同时也可⾃定义弹出框。
特性1.使⽤链式开发代码简洁明了2.所有的弹出框样式都在DialogUIUtils这个类中完成,⽅便查阅⽅法3.可以⾃定义弹出框字体样式4.简单的类似加载框的样式可以⽀持两种主题更改默认⽩⾊和灰⾊截图demo下载demo apk下载Download or grab via Maven:<dependency><groupId>com.dou361.dialogui</groupId> <artifactId>jjdxm-dialogui</artifactId><version>x.x.x</version>or Gradle:compile 'com.dou361.dialogui:jjdxm-dialogui:x.x.x'历史版本:compile 'com.dou361.dialogui:jjdxm-dialogui:1.0.1'compile 'com.dou361.dialogui:jjdxm-dialogui:1.0.0'jjdxm-dialogui requires at minimum Java 9 or Android 2.3.架包的打包引⽤以及冲突解决代码混淆根据你的混淆器配置和使⽤,您可能需要在你的proguard⽂件内配置以下内容:-keep class com.dou361.** {*;}AndroidStudio代码混淆注意的问题快速开始step1如果需要使⽤toast类,采⽤单例模式的,多次调⽤toast后只会显⽰⼀个,需要初始化DialogUIUtils类,否则会抛异常,使⽤前初始化即可,代码如下DialogUIUtils.init(appContext);step2如果不需要使⽤toast类,可以不操作step1,直接使⽤相对于的弹出框即可。
Android开发自定义Dialog(BottomSheetDialog与Dialog)开发记录
Android开发⾃定义Dialog(BottomSheetDialog与Dialog)开发记录前⾔ 记录⼀些⾃⼰项⽬上⾃定义的Dialog基础Dialogpublic class BaseDialog extends Dialog {private float widthRatio = 1f;private ShapeDrawable mShapeDrawable;public BaseDialog(@NonNull Context context) {super(context);}public BaseDialog(@NonNull Context context, int themeResId) {super(context, themeResId);}protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {super(context, cancelable, cancelListener);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);}/*** 设置对话框宽度与屏幕宽度占⽐ 0.0~1.0** @param widthRatio*/public void setWidthRatio(float widthRatio) {this.widthRatio = widthRatio;}@Overrideprotected void onStart() {super.onStart();youtParams layoutParams = getWindow().getAttributes();float width = getContext().getResources().getDisplayMetrics().widthPixels * widthRatio;layoutParams.width = (int) width;getWindow().setAttributes(layoutParams);getWindow().getDecorView().setBackground(new ColorDrawable(Color.TRANSPARENT));}}实现对话框全透明在styles添加<style name="dialogTransparent" parent="@android:style/Theme.Dialog"><item name="android:windowFrame">@null</item><!--边框--><item name="android:windowIsFloating">true</item><!--是否浮现在activity之上--><item name="android:windowIsTranslucent">true</item><!--半透明--><item name="android:windowNoTitle">true</item><!--⽆标题--><item name="android:background">@android:color/transparent</item><!--背景透明--><item name="android:windowBackground">@android:color/transparent</item><!--背景透明--><item name="android:backgroundDimEnabled">true</item><!--模糊--><item name="android:backgroundDimAmount">0.5</item><!--背景透明度0到1 50%就是0.5--></style>将风格添加public class NumberInputDialog extends BottomSheetDialog implements View.OnClickListener {public NumberInputDialog(@NonNull Context context) {super(context,R.style.dialogTransparent);initView();}设置背景透明@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().getDecorView().setBackground(new ColorDrawable(Color.TRANSPARENT));}设置全屏请注意,在开发的时候经常会发现,我们设置的全屏的宽度或者全屏的⾼度后经常外⾯还要⼀些边缘空⽩空间,需要设置setPadding来取消空⽩内边距,代码如下:@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().getDecorView().setPadding(0,0,0,0);//取消内边距空⽩getWindow().setLayout(youtParams.MATCH_PARENT, youtParams.MATCH_PARENT);//设置全屏}或者@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().getDecorView().setPadding(0,0,0,0);//取消内边距空⽩youtParams layoutParams = getWindow().getAttributes();layoutParams.width = youtParams.MATCH_PARENT;layoutParams.height = youtParams.MATCH_PARENT;getWindow().setAttributes(layoutParams);}在取消内边距空⽩后,还有⼀个好处,那就是设置 layoutParams.width 与layoutParams.height 会更加准确设置对话框显⽰位置@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//设置显⽰位置 Gravity.BOTTOM Gravity.TOP Gravity.LEFT Gravity.RIGHT Gravity.CENTERgetWindow().setGravity(Gravity.BOTTOM);}弹出输⼊法并且焦点选中输⼊框EditText editTextTextPersonName = findViewById(R.id.editTextTextPersonName);getWindow().setSoftInputMode(youtParams.SOFT_INPUT_STATE_VISIBLE);//设置输⼊盘可见editTextTextPersonName.requestFocus();设置背景阴影透明度@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);youtParams layoutParams = getWindow().getAttributes();layoutParams.dimAmount = 0f;//调整透明度getWindow().setAttributes(layoutParams);}BottomSheetDialog禁⽤下滑退出private fun showDurationPickerDialog(){val dialog = context?.let { BottomSheetDialog(it) }val binding = DialogDurationPickerBinding.inflate(layoutInflater)dialog?.setContentView(binding.root)binding.root.post {val view = dialog?.findViewById<View>(R.id.design_bottom_sheet)val behavior = view?.let { BottomSheetBehavior.from(it) }behavior?.isHideable = false//略...BottomSheetDialog背景透明(显⽰圆⾓) BottomSheetDialog对话框其实是⾃带⼀个⽩⾊背景的,我们在⾃⼰的布局设置圆⾓shape后会出现不显⽰的情况. val dialog = BottomSheetDialog(this)dialog.setContentView(yout.main_dialog_bottom_wheel)dialog.show()//设置背景透明,需要在show⽅法后⾯dialog.findViewById<View>(R.id.design_bottom_sheet)?.setBackgroundResource(android.R.color.transparent)横屏显⽰不全的问题解决@Overrideprotected void onStart() {super.onStart();if (mIsHorizontal){getBehavior().setState(BottomSheetBehavior.STATE_EXPANDED);}}end。
Android自定义弹出窗口PopupWindow使用技巧
Android⾃定义弹出窗⼝PopupWindow使⽤技巧PopupWindow是Android上⾃定义弹出窗⼝,使⽤起来很⽅便。
PopupWindow的构造函数为复制代码代码如下:public PopupWindow(View contentView, int width, int height, boolean focusable)contentView为要显⽰的view,width和height为宽和⾼,值为像素值,也可以是MATCHT_PARENT和WRAP_CONTENT。
focusable为是否可以获得焦点,这是⼀个很重要的参数,也可以通过public void setFocusable(boolean focusable)来设置,如果focusable为false,在⼀个Activity弹出⼀个PopupWindow,按返回键,由于PopupWindow没有焦点,会直接退出Activity。
如果focusable为true,PopupWindow弹出后,所有的触屏和物理按键都有PopupWindows处理。
如果PopupWindow中有Editor的话,focusable要为true。
下⾯实现⼀个简单的PopupWindow主界⾯的layout为:<RelativeLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:id="@+id/layout_main"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity" ><Buttonandroid:id="@+id/btn_test_popupwindow"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="@string/app_name" /></RelativeLayout>PopupWindow的layout为:<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="#000000" ><TextViewandroid:layout_width="wrap_content"android:layout_height="80dp"android:text="@string/app_name"android:textColor="#ffffffff"android:layout_centerInParent="true"android:gravity="center"/></RelativeLayout>Activity的代码为:public class MainActivity extends Activity {private Button mButton;private PopupWindow mPopupWindow;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);View popupView = getLayoutInflater().inflate(yout_popupwindow, null);mPopupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);mPopupWindow.setTouchable(true);mPopupWindow.setOutsideTouchable(true);mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));mButton = (Button) findViewById(R.id.btn_test_popupwindow);mButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {mPopupWindow.showAsDropDown(v);}});}}这三⾏代码mPopupWindow.setTouchable(true);mPopupWindow.setOutsideTouchable(true);mPopupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));的作⽤是点击空⽩处的时候PopupWindow会消失。
android弹出窗口的实现(PopupWindow)
接下来定义弹出对话框的布局文件group_list.xml和group_item_view.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/group_bg" android:orientation="vertical" > <ImageView android:id="@+id/iv_group_list_bg_divider" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/group_divider" /> <ListView android:id="@+id/lvGroup" android:layout_width="fill_parent" android:layout_height="fill_parent" android:divider="@drawable/group_divider" /></LinearLayout>
android dialogfragment简书
android dialogfragment简书【实用版】目录1.Android DialogFragment 简介2.DialogFragment 与 Fragment 的区别3.DialogFragment 的创建与使用4.DialogFragment 的优点与局限性5.简书对于 DialogFragment 的使用案例正文1.Android DialogFragment 简介DialogFragment 是 Android 系统中一种特殊的 Fragment,用于实现对话框(Dialog)的功能。
与普通的 Fragment 不同,DialogFragment 可以在用户界面中独立显示,不依赖于 Activity 的生命周期。
DialogFragment 通常用于实现对用户友好的提示、警告、确认等操作。
2.DialogFragment 与 Fragment 的区别DialogFragment 与普通 Fragment 在功能和用途上有明显的区别。
普通 Fragment 是 Activity 中的一个组成部分,可以与 Activity 共享生命周期,而 DialogFragment 则相对独立,可以独立显示和消失。
DialogFragment 主要用于实现对话框功能,而普通 Fragment 则用于构建应用的基本界面。
3.DialogFragment 的创建与使用要创建一个 DialogFragment,首先需要继承android.app.DialogFragment 类,并重写其 onCreateDialog 方法。
在onCreateDialog 方法中,可以通过 Inflater 实例创建一个对话框布局(Layout),并设置对话框的标题、内容和按钮等属性。
最后,调用setContentView 方法将布局设置为 DialogFragment 的内容视图。
使用 DialogFragment 时,通常需要通过 FragmentManager 来将其添加到 Activity 中。
android dialog用法
android dialog用法Android Dialog用法简介Android Dialog是一种用于显示简单消息、提示信息或者与用户进行交互的弹出窗口。
使用Dialog可以在不离开当前页面的情况下进行一些操作或者获取一些信息。
在本文中,我们将解释一些常见的Android Dialog用法,帮助您更好地使用和定制Dialog。
AlertDialog基本用法AlertDialog是Android中最常见的一种Dialog类型。
它是一个模态对话框,可以显示一条消息以及确定和取消按钮。
builder = new (this);("提示").setMessage("是否删除该文件?").setPositiveButton("确定", new () {public void onClick(DialogInterface dialog, i nt id) {// 用户点击确定按钮的操作}}).setNegativeButton("取消", new () {public void onClick(DialogInterface dialog, i nt id) {// 用户点击取消按钮的操作}});AlertDialog dialog = ();();自定义布局除了使用默认的消息和按钮之外,还可以用自定义的布局来渲染AlertDialog。
builder = new (this);LayoutInflater inflater = getLayoutInflater();View dialogView = (_dialog, null);(dialogView).setPositiveButton("保存", new () {public void onClick(DialogInterface dialog, i nt id) {// 用户点击保存按钮的操作}}).setNegativeButton("取消", new () {public void onClick(DialogInterface dialog, i nt id) {// 用户点击取消按钮的操作}});AlertDialog dialog = ();();ProgressDialog基本用法ProgressDialog是一种显示进度的Dialog,适用于需要执行长时间任务或加载数据的情况。
android自定义Dialog弹框和背景阴影显示效果
android⾃定义Dialog弹框和背景阴影显⽰效果本⽂实例为⼤家分享了android⾃定义Dialog弹框和背景阴影显⽰的具体代码,供⼤家参考,具体内容如下⾸先需要⾃定义⼀个类,继承Dialogimport android.app.Dialog;import android.content.Context;import android.os.Bundle;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager;import android.widget.Button;import android.widget.TextView;import com.zhiziyun.dmptest.bot.R;/*** Created by Administrator on 2018/1/31.*/public class CustomDialog extends Dialog {private Button yes, no;//确定按钮private TextView titleTv;//消息标题⽂本private TextView messageTv;//消息提⽰⽂本private String titleStr;//从外界设置的title⽂本private String messageStr;//从外界设置的消息⽂本//确定⽂本和取消⽂本的显⽰内容private String yesStr, noStr;private onNoOnclickListener noOnclickListener;//取消按钮被点击了的监听器private onYesOnclickListener yesOnclickListener;//确定按钮被点击了的监听器/*** 设置取消按钮的显⽰内容和监听** @param str* @param onNoOnclickListener*/public void setNoOnclickListener(String str, onNoOnclickListener onNoOnclickListener) {if (str != null) {noStr = str;}this.noOnclickListener = onNoOnclickListener;}/*** 设置确定按钮的显⽰内容和监听** @param str* @param onYesOnclickListener*/public void setYesOnclickListener(String str, onYesOnclickListener onYesOnclickListener) { if (str != null) {yesStr = str;}this.yesOnclickListener = onYesOnclickListener;}public CustomDialog(Context context) {super(context, R.style.Dialog_Msg);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.dialog_custom);//按空⽩处不能取消动画setCanceledOnTouchOutside(false);//初始化界⾯控件initView();//初始化界⾯数据initData();//初始化界⾯控件的事件initEvent();}/*** 初始化界⾯的确定和取消监听器*/private void initEvent() {//设置确定按钮被点击后,向外界提供监听yes.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (yesOnclickListener != null) {yesOnclickListener.onYesClick();}}});no.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (noOnclickListener != null) {noOnclickListener.onNoClick();}}});}/*** 初始化界⾯控件的显⽰数据*/private void initData() {//如果⽤户⾃定了title和messageif (titleStr != null) {titleTv.setText(titleStr);}if (messageStr != null) {messageTv.setText(messageStr);}//如果设置按钮的⽂字if (yesStr != null) {yes.setText(yesStr);}}/*** 初始化界⾯控件*/private void initView() {yes = (Button) findViewById(R.id.yes);no = (Button) findViewById(R.id.no);titleTv = (TextView) findViewById(R.id.title);messageTv = (TextView) findViewById(R.id.message);}/*** 从外界Activity为Dialog设置标题** @param title*/public void setTitle(String title) {titleStr = title;}/*** 从外界Activity为Dialog设置dialog的message** @param message*/public void setMessage(String message) {messageStr = message;}/*** 设置确定按钮和取消被点击的接⼝*/public interface onYesOnclickListener {public void onYesClick();}public interface onNoOnclickListener {public void onNoClick();}@Overridepublic void show() {super.show();/*** 设置宽度全屏,要设置在show的后⾯*/youtParams layoutParams = getWindow().getAttributes();layoutParams.width= youtParams.MATCH_PARENT;layoutParams.height= youtParams.MATCH_PARENT;getWindow().getDecorView().setPadding(0, 0, 0, 0);getWindow().setAttributes(layoutParams);}}这是实体类中的style:<style name="custom_dialog_style" parent="android:Theme.Dialog"><item name="android:windowFrame">@null</item><item name="android:windowIsFloating">true</item><item name="android:windowIsTranslucent">false</item><item name="android:windowNoTitle">true</item><!--除去title--><item name="android:backgroundDimEnabled">true</item><!--半透明--><item name="android:windowBackground">@color/transparent</item><!--除去背景⾊--> <item name="android:radius">10dp</item></style>其中@color/transparent是⼀个透明⾊<color name="transparent">#00000000</color>然后是布局<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#A5000000"><LinearLayoutandroid:layout_width="260dp"android:layout_height="wrap_content"android:layout_centerInParent="true"android:background="@drawable/shape_dialog_msg"android:orientation="vertical"><TextViewandroid:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_margin="15dp"android:gravity="center"android:text="消息提⽰"android:textColor="@color/colorBlack"android:textSize="@dimen/title_text_size" /><TextViewandroid:id="@+id/message"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_marginLeft="@dimen/padding_left_right4"android:layout_marginRight="@dimen/padding_left_right4"android:text="提⽰消息"android:textColor="@color/colorBlack"android:textSize="@dimen/textsizi3" /><Viewandroid:layout_width="match_parent"android:layout_height="1px"android:layout_marginTop="15dp"android:background="#E4E4E4" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="@dimen/buttom_height"android:orientation="horizontal"><Buttonandroid:id="@+id/no"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@null"android:gravity="center"android:singleLine="true"android:text="取消"android:textColor="@color/blue"android:textSize="@dimen/textsizi3" /><Buttonandroid:id="@+id/yes"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_weight="1"android:background="@null"android:gravity="center"android:singleLine="true"android:text="确定"android:textColor="@color/red"android:textSize="@dimen/textsizi3" /></LinearLayout></LinearLayout></RelativeLayout>下⾯是shape_dialog_msg的代码<?xml version="1.0" encoding="UTF-8"?><selector xmlns:android="/apk/res/android"> <item android:state_pressed="false"><shape android:shape="rectangle" ><!-- 填充的颜⾊前两位是透明度--><solid android:color="#f7f6f6"></solid><!-- 设置按钮的四个⾓为弧形 --><!-- android:radius 弧形的半径 --><corners android:radius="8dip" /><!-- padding:Button⾥⾯的⽂字与Button边界的间隔 --><padding android:bottom="2dp" android:left="2dp" android:right="2dp" android:top="2dp" /></shape></item></selector>准备⼯作都做好了,下⾯就是如何使⽤了//点击弹出对话框final CustomDialog customDialog = new CustomDialog(getActivity());customDialog.setTitle("消息提⽰");customDialog.setMessage("是否暂停⼴告投放?");customDialog.setYesOnclickListener("确定", new CustomDialog.onYesOnclickListener() {@Overridepublic void onYesClick() {//这⾥是确定的逻辑代码,别忘了点击确定后关闭对话框customDialog.dismiss();}});customDialog.setNoOnclickListener("取消", new CustomDialog.onNoOnclickListener() {@Overridepublic void onNoClick() {customDialog.dismiss();}});customDialog.show();以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
Android修改Dialog样式的方法
Android修改Dialog样式的⽅法⽬录⼀、Dialog源码解析1.1 new AlertDialog.Builder(this).create()1.2 AlertController⼆、修改Dialog样式2.1 通过findViewById2.2 ⾃定义style⼀、Dialog源码解析1.1 new AlertDialog.Builder(this).create()protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) {super(context, resolveDialogTheme(context, themeResId));//创建AlertController,是Dialog布局相关代码mAlert = new AlertController(getContext(), this, getWindow());}@NonNullpublic AlertDialog create() {// We can't use Dialog's 3-arg constructor with the createThemeContextWrapper param,// so we always have to re-set the themefinal AlertDialog dialog = new AlertDialog(P.mContext, mTheme);P.apply(dialog.mAlert);dialog.setCancelable(P.mCancelable);if (P.mCancelable) {dialog.setCanceledOnTouchOutside(true);}dialog.setOnCancelListener(P.mOnCancelListener);dialog.setOnDismissListener(P.mOnDismissListener);if (P.mOnKeyListener != null) {dialog.setOnKeyListener(P.mOnKeyListener);}return dialog;}public void apply(AlertController dialog) {if (mCustomTitleView != null) {dialog.setCustomTitle(mCustomTitleView);} else {if (mTitle != null) {dialog.setTitle(mTitle);}if (mIcon != null) {dialog.setIcon(mIcon);}if (mIconId != 0) {dialog.setIcon(mIconId);}..........AlertDialog 构造函数中会创建 AlertController,⽤来控制对话框的布局P.apply(dialog.mAlert); 将⽤户⾃定义的配置赋值给 AlertController1.2 AlertControllerpublic AlertController(Context context, AppCompatDialog di, Window window) {mContext = context;mDialog = di;mWindow = window;mHandler = new ButtonHandler(di);final TypedArray a = context.obtainStyledAttributes(null, R.styleable.AlertDialog,R.attr.alertDialogStyle, 0);mAlertDialogLayout = a.getResourceId(R.styleable.AlertDialog_android_layout, 0);mButtonPanelSideLayout = a.getResourceId(R.styleable.AlertDialog_buttonPanelSideLayout, 0);mListLayout = a.getResourceId(R.styleable.AlertDialog_listLayout, 0);mMultiChoiceItemLayout = a.getResourceId(R.styleable.AlertDialog_multiChoiceItemLayout, 0); mSingleChoiceItemLayout = a.getResourceId(R.styleable.AlertDialog_singleChoiceItemLayout, 0);mListItemLayout = a.getResourceId(R.styleable.AlertDialog_listItemLayout, 0);mShowTitle = a.getBoolean(R.styleable.AlertDialog_showTitle, true);mButtonIconDimen = a.getDimensionPixelSize(R.styleable.AlertDialog_buttonIconDimen, 0); a.recycle();/* We use a custom title so never request a window title */di.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);}R.attr.alertDialogStyle 是对话框的默认样式,<item name="alertDialogStyle">@style/AlertDialog.AppCompat</item><style name="AlertDialog.AppCompat" parent="Base.AlertDialog.AppCompat"/><style name="Base.AlertDialog.AppCompat" parent="android:Widget"><item name="android:layout">@layout/abc_alert_dialog_material</item><item name="listLayout">@layout/abc_select_dialog_material</item><item name="listItemLayout">@layout/select_dialog_item_material</item><item name="multiChoiceItemLayout">@layout/select_dialog_multichoice_material</item><item name="singleChoiceItemLayout">@layout/select_dialog_singlechoice_material</item> <item name="buttonIconDimen">@dimen/abc_alert_dialog_button_dimen</item></style>上述代码可以看出,abc_alert_dialog_material 就是dialog的默认布局。
Android中自定义对话框(Dialog)
Android中自定义对话框(Dialog)1.修改系统默认的Dialog样式(风格、主题)2.自定义Dialog布局文件3.可以自己封装一个类,继承自Dialog或者直接使用Dialog类来实现,为了方便以后重复使用,建议自己封装一个Dialog类第一步:我们知道Android定义个控件或View的样式都是通过定义其style来实现的,查看Android框架中的主题文件,在源码中的路径:/frameworks/base/core/res/res/values/themes.xml,我们可以看到,Android为Dialog定义了一个样式,<style name="Theme.Dialog"><item name="android:windowFrame">@null</item><itemname="android:windowTitleStyle">@android:style/DialogWind owTitle</item><itemname="android:windowBackground">@android:drawable/pane l_background</item><item name="android:windowIsFloating">true</item><itemname="android:windowContentOverlay">@null</item> <itemname="android:windowAnimationStyle">@android:style/Anima tion.Dialog</item><itemname="android:windowSoftInputMode">stateUnspecified|adjus tPan</item></style>我们可以看到,在Themes.xml中定义的Dialog的样式,其中,定义了window的标题样式,window的背景图,是否悬浮等等。
android自定义弹出框样式的实现方法
android⾃定义弹出框样式的实现⽅法前⾔:做项⽬时,感觉android⾃带的弹出框样式⽐较丑,很多应⽤都是⾃⼰做的弹出框,这⾥也试着⾃⼰做了⼀个。
废话不说先上图⽚:实现机制1.先⾃定义⼀个弹出框的样式2.⾃⼰实现CustomDialog类,继承⾃Dialog,实现⾥⾯⽅法,在⾥⾯加载⾃定义样式的弹出框;3.使⽤时,与使⽤Dialog⼀样具体代码dialog_normal_layout.xml样式⽂件<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:clickable="true"android:orientation="vertical"android:padding="20.0dip" ><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:background="@drawable/bg_bombbox"android:orientation="vertical" ><TextViewandroid:id="@+id/title"style="@style/text_18_ffffff"android:layout_width="fill_parent"android:layout_height="40.0dip"android:gravity="center"android:text="@string/title_alert"android:visibility="visible" /><LinearLayoutandroid:id="@+id/content"android:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="center" ><TextViewandroid:id="@+id/message"style="@style/text_16_666666"android:layout_width="fill_parent"android:layout_height="wrap_content"android:gravity="left|center"android:lineSpacingMultiplier="1.5"android:minHeight="120.0dip"android:paddingBottom="15.0dip"android:paddingLeft="20.0dip"android:paddingRight="20.0dip"android:paddingTop="15.0dip" /></LinearLayout><Viewandroid:layout_width="fill_parent"android:layout_height="1.0px"android:background="#ffd0d0d0" /><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="60.0dip"android:layout_gravity="bottom"android:background="@drawable/dialog_bottom_bg"android:gravity="center"android:orientation="horizontal" ><Buttonandroid:id="@+id/positiveButton"style="@style/text_15_ffffff_sdw"android:layout_width="114.0dip"android:layout_height="40.0dip"android:background="@drawable/btn_ok_selector"android:gravity="center"android:text="@string/ok" /><Buttonandroid:id="@+id/negativeButton"style="@style/text_15_666666_sdw"android:layout_width="114.0dip"android:layout_height="40.0dip"android:layout_marginLeft="20.0dip"android:background="@drawable/btn_cancel_selector"android:gravity="center"android:text="@string/cancel" /></LinearLayout></LinearLayout></FrameLayout>其中引⽤的样式⽂件styles.xml<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="/apk/res/android"> <style name="AppBaseTheme" parent="android:Theme.Light"></style> <style name="AppTheme" parent="AppBaseTheme"></style><style name="text_18_ffffff"><item name="android:textSize">18.0dip</item><item name="android:textColor">#ffffffff</item></style><style name="text_16_666666"><item name="android:textSize">16.0dip</item><item name="android:textColor">#ff666666</item></style><style name="sdw_white"><item name="android:shadowColor">#7fffffff</item><item name="android:shadowDx">0.0</item><item name="android:shadowDy">0.65</item><item name="android:shadowRadius">1.0</item></style><style name="sdw_79351b"><item name="android:shadowColor">#ff79351b</item><item name="android:shadowDx">0.0</item><item name="android:shadowDy">1.0</item><item name="android:shadowRadius">1.0</item></style><style name="text_15_ffffff_sdw" parent="@style/sdw_79351b"><item name="android:textSize">15.0dip</item><item name="android:textColor">#ffffffff</item></style><style name="text_15_666666_sdw" parent="@style/sdw_white"><item name="android:textSize">15.0dip</item><item name="android:textColor">#ff666666</item></style><style name="Dialog" parent="android:style/Theme.Dialog"><item name="android:background">#00000000</item><item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowNoTitle">true</item><item name="android:windowIsFloating">true</item></style></resources>⾃定义Dialog的实现类CustomDialogpackage com.dyr.custom;import android.app.Dialog;import android.content.Context;import android.content.DialogInterface;import youtInflater;import android.view.View;import youtParams;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;import com.dyr.view.R;public class CustomDialog extends Dialog {public CustomDialog(Context context) {super(context);}public CustomDialog(Context context, int theme) {super(context, theme);}public static class Builder {private Context context;private String title;private String message;private String positiveButtonText;private String negativeButtonText;private View contentView;private DialogInterface.OnClickListener positiveButtonClickListener;private DialogInterface.OnClickListener negativeButtonClickListener;public Builder(Context context) {this.context = context;}public Builder setMessage(String message) {this.message = message;return this;}/*** Set the Dialog message from resource** @param title* @return*/public Builder setMessage(int message) {this.message = (String) context.getText(message);return this;}/*** Set the Dialog title from resource** @param title* @return*/public Builder setTitle(int title) {this.title = (String) context.getText(title);return this;}/*** Set the Dialog title from String** @param title* @return*/public Builder setTitle(String title) {this.title = title;return this;}public Builder setContentView(View v) {this.contentView = v;return this;}/*** Set the positive button resource and it's listener** @param positiveButtonText* @return*/public Builder setPositiveButton(int positiveButtonText,DialogInterface.OnClickListener listener) {this.positiveButtonText = (String) context.getText(positiveButtonText);this.positiveButtonClickListener = listener;return this;}public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) {this.positiveButtonText = positiveButtonText;this.positiveButtonClickListener = listener;return this;}public Builder setNegativeButton(int negativeButtonText,DialogInterface.OnClickListener listener) {this.negativeButtonText = (String) context.getText(negativeButtonText);this.negativeButtonClickListener = listener;return this;}public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) {this.negativeButtonText = negativeButtonText;this.negativeButtonClickListener = listener;return this;}public CustomDialog create() {LayoutInflater inflater = (LayoutInflater) context.getSystemService(YOUT_INFLATER_SERVICE);// instantiate the dialog with the custom Themefinal CustomDialog dialog = new CustomDialog(context,R.style.Dialog);View layout = inflater.inflate(yout.dialog_normal_layout, null);dialog.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));// set the dialog title((TextView) layout.findViewById(R.id.title)).setText(title);// set the confirm buttonif (positiveButtonText != null) {((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);if (positiveButtonClickListener != null) {((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener() {public void onClick(View v) {positiveButtonClickListener.onClick(dialog,DialogInterface.BUTTON_POSITIVE);}});}} else {// if no confirm button just set the visibility to GONElayout.findViewById(R.id.positiveButton).setVisibility(View.GONE);}// set the cancel buttonif (negativeButtonText != null) {((Button) layout.findViewById(R.id.negativeButton)).setText(negativeButtonText);if (negativeButtonClickListener != null) {((Button) layout.findViewById(R.id.negativeButton)).setOnClickListener(new View.OnClickListener() {public void onClick(View v) {negativeButtonClickListener.onClick(dialog,DialogInterface.BUTTON_NEGATIVE);}});}} else {// if no confirm button just set the visibility to GONElayout.findViewById(R.id.negativeButton).setVisibility(View.GONE);}// set the content messageif (message != null) {((TextView) layout.findViewById(R.id.message)).setText(message);} else if (contentView != null) {// if no message set// add the contentView to the dialog body((LinearLayout) layout.findViewById(R.id.content)).removeAllViews();((LinearLayout) layout.findViewById(R.id.content)).addView(contentView, new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); }dialog.setContentView(layout);return dialog;}}}使⽤代码CustomDialog.Builder builder = new CustomDialog.Builder(this);builder.setMessage("这个就是⾃定义的提⽰框");builder.setTitle("提⽰");builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {dialog.dismiss();//设置你的操作事项}});builder.setNegativeButton("取消",new android.content.DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});builder.create().show();⾄此,⾃定义弹出框已经完成,是不是感觉很简单呢。
Android 适应任何自定义样式 提示弹出框 Dialog 封装
Android 适应任何样式提示弹出框Dialog 封装在Android开发中,难免有各种各样的提示框,如加载数据等待框,删除确认框、输入密码提示框等等,这些是完全可以自定义的,这里给出一个框架以及一个示例,帮助你开发任何样式布局的提示框,废话不多说,直接贴代码:HintDialog.javaimport android.app.AlertDialog;import android.app.Dialog;import android.content.Context;import android.view.KeyEvent;import android.view.Window;public class HintDialog{Dialog mDialog = null;private Context mContext = null;private IHintDialog mIDialogInstance = null;/*** 构造函数* @param context*/public HintDialog(Context context){mContext = context;mDialog = new AlertDialog(mContext){@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event){if (keyCode == KeyEvent.KEYCODE_BACK &&mIDialogInstance != null){mIDialogInstance.onKeyDown(keyCode, event);return true;}return super.onKeyDown(keyCode, event);}};mDialog.setCancelable(false);mDialog.setCanceledOnTouchOutside(false);}/**** @param iLayoutResId 此DIALOG采用的布局文件* @param interfaceInstance 此DIALOG需要实现的一些接口事件 */public void showDialog(int iLayoutResId, IHintDialog interfaceInstance){if (mDialog == null || iLayoutResId == 0){return;}mIDialogInstance = interfaceInstance;mDialog.show();mDialog.setContentView(iLayoutResId);Window window = mDialog.getWindow();if (mIDialogInstance != null){mIDialogInstance.showWindowDetail(window);}}/*** 使dialog消失*/public void dismissDialog(){if (mDialog != null && mDialog.isShowing()){mDialog.dismiss();}}/*** 确定Dialog是否正在显示* @returnpublic boolean isShowing(){if (mDialog != null && mDialog.isShowing()){return mDialog.isShowing();}return false;}public interface IHintDialog{public void onKeyDown(int keyCode, KeyEvent event);public void showWindowDetail(Window window);}}HintDialogActivity.javaimport com.example.hintdialogdemo.HintDialog.IHintDialog;import android.os.Bundle;import android.app.Activity;import android.view.KeyEvent;import android.view.Menu;import android.view.View;import android.view.Window;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class HintDialogActivity extends Activity implements OnClickListener{Button btnConfirm = null;HintDialog mDialog = null;@Overridepublic void onCreate(Bundle savedInstanceState)super.onCreate(savedInstanceState);setContentView(yout.activity_hint_dialog);btnConfirm = (Button) findViewById(R.id.button1);btnConfirm.setOnClickListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu){getMenuInflater().inflate(R.menu.activity_hint_dialog, menu);return true;}@Overridepublic void onClick(View v){switch (v.getId()){case R.id.button1:mDialog = new HintDialog(HintDialogActivity.this);mDialog.showDialog(yout.confirm_dialog, new IHintDialog(){@Overridepublic void showWindowDetail(Window window){TextView txvTitle = (TextView) window.findViewById(R.id.txvTitle);txvTitle.setText("Confirm?");Button btnOK = (Button)window.findViewById(R.id.btnOK);btnOK.setText("Yes");btnOK.setOnClickListener(HintDialogActivity.this);Button btnCancel = (Button) window.findViewById(R.id.btnCancel);btnCancel.setText("NO");btnCancel.setOnClickListener(HintDialogActivity.this);}@Overridepublic void onKeyDown(int keyCode, KeyEvent event){if (keyCode == KeyEvent.KEYCODE_BACK){mDialog.dismissDialog();Toast.makeText(HintDialogActivity.this,"onKeyback now",Toast.LENGTH_LONG).show();}}});break;case R.id.btnOK:mDialog.dismissDialog();Toast.makeText(HintDialogActivity.this,"Confirm OK now", Toast.LENGTH_LONG).show();break;case R.id.btnCancel:mDialog.dismissDialog();Toast.makeText(HintDialogActivity.this,"Confirm Cancel now", Toast.LENGTH_LONG).show();break;default:break;}}}其实也不难,主要是AlertDialog的使用,注意需要显示调用dissmissDialog()来消失此弹出框。
android常用对话框封装
android常⽤对话框封装在android开发中,经常会⽤到对话框跟⽤户进⾏交互,⽅便⽤户可操作性;接下来就对常⽤对话框进⾏简单封装,避免在项⽬中出现冗余代码,加重后期项⽬的维护量;代码如有问题欢迎⼤家拍砖指正⼀起进步。
先贴出演⽰结果,在晒出演⽰代码。
1、运⾏成功后,原始界⾯如下:2、点击“显⽰普通对话框”,效果界⾯如下:3、点击“显⽰列表对话框”,效果界⾯如下:4、点击“显⽰单选按钮对话框”,效果界⾯如下:5、点击“显⽰复选对话框”,效果界⾯如下:代码:1、项⽬⽬录结构如下2、对话框封装类DialogToolpackage com.hrtx.util;import android.app.Dialog;import android.content.Context;import android.content.DialogInterface.OnClickListener;/*** 对话框封装类** @author jiqinlin**/public class DialogTool {/*** 创建普通对话框** @param ctx 上下⽂必填* @param iconId 图标,如:R.drawable.icon 必填* @param title 标题必填* @param message 显⽰内容必填* @param btnName 按钮名称必填* @param listener 监听器,需实现android.content.DialogInterface.OnClickListener接⼝必填* @return*/public static Dialog createNormalDialog(Context ctx,int iconId,String title,String message,String btnName,OnClickListener listener) {Dialog dialog=null;android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);// 设置对话框的图标builder.setIcon(iconId);// 设置对话框的标题builder.setTitle(title);// 设置对话框的显⽰内容builder.setMessage(message);// 添加按钮,android.content.DialogInterface.OnClickListener.OnClickListenerbuilder.setPositiveButton(btnName, listener);// 创建⼀个普通对话框dialog = builder.create();return dialog;}/*** 创建列表对话框** @param ctx 上下⽂必填* @param iconId 图标,如:R.drawable.icon 必填* @param title 标题必填* @param itemsId 字符串数组资源id 必填* @param listener 监听器,需实现android.content.DialogInterface.OnClickListener接⼝必填* @return*/public static Dialog createListDialog(Context ctx,int iconId,String title,int itemsId,OnClickListener listener) {Dialog dialog=null;android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);// 设置对话框的图标builder.setIcon(iconId);// 设置对话框的标题builder.setTitle(title);// 添加按钮,android.content.DialogInterface.OnClickListener.OnClickListenerbuilder.setItems(itemsId, listener);// 创建⼀个列表对话框dialog = builder.create();return dialog;}/*** 创建单选按钮对话框** @param ctx 上下⽂必填* @param iconId 图标,如:R.drawable.icon 必填* @param title 标题必填* @param itemsId 字符串数组资源id 必填* @param listener 单选按钮项监听器,需实现android.content.DialogInterface.OnClickListener接⼝必填* @param btnName 按钮名称必填* @param listener2 按钮监听器,需实现android.content.DialogInterface.OnClickListener接⼝必填* @return*/public static Dialog createRadioDialog(Context ctx,int iconId,String title,int itemsId,OnClickListener listener,String btnName,OnClickListener listener2) {Dialog dialog=null;android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);// 设置对话框的图标builder.setIcon(iconId);// 设置对话框的标题builder.setTitle(title);// 0: 默认第⼀个单选按钮被选中builder.setSingleChoiceItems(itemsId, 0, listener);// 添加⼀个按钮builder.setPositiveButton(btnName, listener2) ;// 创建⼀个单选按钮对话框dialog = builder.create();return dialog;}/*** 创建复选对话框** @param ctx 上下⽂必填* @param iconId 图标,如:R.drawable.icon 必填* @param title 标题必填* @param itemsId 字符串数组资源id 必填* @param flags 初始复选情况必填* @param listener 单选按钮项监听器,需实现android.content.DialogInterface.OnMultiChoiceClickListener接⼝必填 * @param btnName 按钮名称必填* @param listener2 按钮监听器,需实现android.content.DialogInterface.OnClickListener接⼝必填* @return*/public static Dialog createCheckBoxDialog(Context ctx,int iconId,String title,int itemsId,boolean[] flags,android.content.DialogInterface.OnMultiChoiceClickListener listener,String btnName,OnClickListener listener2) {Dialog dialog=null;android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);// 设置对话框的图标builder.setIcon(iconId);// 设置对话框的标题builder.setTitle(title);builder.setMultiChoiceItems(itemsId, flags, listener);// 添加⼀个按钮builder.setPositiveButton(btnName, listener2) ;// 创建⼀个复选对话框dialog = builder.create();return dialog;}}3、对话框Activity类DialogActivitypackage com.ljq.activity;import android.app.Activity;import android.app.Dialog;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;/*** 对话框Activity类** @author jiqinlin**/public class DialogActivity extends Activity {private boolean[] flags=new boolean[]{false,true,false}; //初始复选情况private String[] items=null;private EditText etText=null;private Button btnNormal=null;private Button btnList=null;private Button btnRadio=null;private Button btnCheckBox=null;private static final int DIALOG_NORMAL=0; //普通对话框常量private static final int DIALOG_LIST=1; //列表对话框常量private static final int DIALOG_RADIO=2; //单选按钮对话框常量private static final int DIALOG_CHECKBOX=3; //复选对话框常量@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);items=getResources().getStringArray(R.array.hobby);etText=(EditText)findViewById(R.id.etText);btnNormal=(Button)findViewById(R.id.btnNormal);btnList=(Button)findViewById(R.id.btnList);btnRadio=(Button)findViewById(R.id.btnRadio);btnCheckBox=(Button)findViewById(R.id.btnCheckBox);btnNormal.setOnClickListener(l);btnList.setOnClickListener(l);btnRadio.setOnClickListener(l);btnCheckBox.setOnClickListener(l);}@Overrideprotected Dialog onCreateDialog(int id) {Dialog dialog=null;switch (id) {case DIALOG_NORMAL: //创建普通对话框dialog = DialogTool.createNormalDialog(this,R.drawable.icon,"普通对话框","这是普通对话框中的内容!"," 确定 ",new android.content.DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {etText.setText("这是普通对话框中的内容!");return;}});break;case DIALOG_LIST: // 创建列表对话框dialog = DialogTool.createListDialog(this,R.drawable.icon,"列表对话框",R.array.hobby,new android.content.DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which) {String hoddy=getResources().getStringArray(R.array.hobby)[which]; etText.setText("您选择了: "+hoddy);return;}});break;case DIALOG_RADIO: // 创建单选按钮对话框dialog=DialogTool.createRadioDialog(this,R.drawable.icon,"单选按钮对话框",R.array.hobby,new android.content.DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {String hoddy = getResources().getStringArray(R.array.hobby)[which];etText.setText("您选择了: " + hoddy);return;}}," 确定 ",new android.content.DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogActivity.this,"您按了确定按钮!", Toast.LENGTH_LONG).show();return;}});break;case DIALOG_CHECKBOX: // 创建复选框对话框dialog=DialogTool.createCheckBoxDialog(this,R.drawable.icon,"复选对话框",R.array.hobby,flags,new DialogInterface.OnMultiChoiceClickListener() {public void onClick(DialogInterface dialog, int which, boolean isChecked) {flags[which] = isChecked;String result = "您选择了:";for (int i = 0; i < flags.length; i++) {if (flags[i]) {result = result + items[i] + "、";}}etText.setText(result.substring(0, result.length() - 1));}}," 确认 ",new android.content.DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(DialogActivity.this, "您按了确定按钮!", Toast.LENGTH_LONG).show(); return;}});break;}return dialog;}//按钮监听View.OnClickListener l = new View.OnClickListener() {@Overridepublic void onClick(View v) {Button btn = (Button) v;switch (btn.getId()) {case R.id.btnNormal: //普通对话框//显⽰对话框showDialog(DIALOG_NORMAL);break;case R.id.btnList: //列表对话框//显⽰对话框showDialog(DIALOG_LIST);break;case R.id.btnRadio: //单选按钮对话框//显⽰对话框showDialog(DIALOG_RADIO);break;case R.id.btnCheckBox: //复选对话框//显⽰对话框showDialog(DIALOG_CHECKBOX);break;}}};}4、布局⽂件main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><EditText android:text=""android:id="@+id/etText"android:layout_width="fill_parent"android:layout_height="wrap_content"android:editable="false"android:cursorVisible="false" /><Button android:text="显⽰普通对话框"android:id="@+id/btnNormal"android:layout_width="fill_parent"android:layout_height="wrap_content" /><Button android:text="显⽰列表话框"android:id="@+id/btnList"android:layout_width="fill_parent"android:layout_height="wrap_content" /><Button android:text="显⽰单选按钮对话框"android:id="@+id/btnRadio"android:layout_width="fill_parent"android:layout_height="wrap_content" /><Button android:text="显⽰复选对话框"android:id="@+id/btnCheckBox"android:layout_width="fill_parent"android:layout_height="wrap_content" /></LinearLayout>5、数组变量array.xml<?xml version="1.0" encoding="utf-8"?><!--resources的使⽤resoureces就是res⽬录下的那些⽬录和⽂件,常⽤的有:res/drawable/ ⽤来存放图⽚⽂件res/layout/ ⽤来存放布局定义⽂件res/values/ ⽤来存放⼀些变量、参数等⽂件--><resources><string-array name="hobby"><item>游泳</item><item>打篮球</item><item>登⼭</item></string-array></resources>6、清单⽂件<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android"package="com.ljq.activity"android:versionCode="1"android:versionName="1.0"><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".DialogActivity"android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity></application><uses-sdk android:minSdkVersion="4" /></manifest>。
详解Android8.1.0Service中弹出Dialog的方法
详解Android8.1.0Service中弹出Dialog的⽅法场景:在Service 中开启线程下载升级包,当下载完系统升级包,弹出⼀个Dialog 提⽰⽤户。
注意,Android 系统版本不⼀样,可能会有不⼀样的表现。
当前是基于 Android 8.1.0 的 Service 中弹 Dialog。
⾸先,就是要在功能清单列表中声明权限,以下两个都必须声明:<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/><!--这⾏代码必须存在,否则点击不了系统设置中的按钮--><uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />然后必须要在MainActivity 进⾏初始化的时候,再次检查⼀下当前应⽤有没有被允许显⽰在其他应⽤上层,这⼀步必不可少。
因为当前基于 Android 8.1.0,⾃从Android 6.0 以后,Google 就对⼀些敏感权限做了收敛,⽐如访问SD卡权限,只是在功能清单列表中声明权限是不够的,还要在应⽤运⾏期间动态检查是否被授权,需注意当检查出来应⽤未被授予这些权限,还要提醒⽤户可能有⼀些功能⽆法使⽤,这个需要注意。
private void checkMyPermission() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (!Settings.canDrawOverlays(this)) {Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:" + getPackageName()));startActivityForResult(intent, 1);}}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == 1) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (Settings.canDrawOverlays(this)) {Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();}else {// SYSTEM_ALERT_WINDOW permission not granted...Toast.makeText(this, "未被授予权限,相关功能不可⽤", Toast.LENGTH_SHORT).show();}}}}接下来,在 Service 中,做如下操作://在 Service 中创建全局变量 mHandlerprivate Handler mHandler;//在 Service ⽣命周期⽅法 onCreate() 中初始化 mHandlermHandler = new Handler(Looper.getMainLooper());//在⼦线程中想要 Toast 的地⽅添加如下mHandler.post(new Runnable() {@Overridepublic void run() {//show dialogjustShowDialog();}});private void justShowDialog() {AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()).setIcon(android.R.drawable.ic_dialog_info).setTitle("service中弹出Dialog了").setMessage("是否关闭dialog?").setPositiveButton("确定",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int whichButton) {}}).setNegativeButton("取消",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int whichButton) {}});//下⾯这⾏代码放到⼦线程中会 Can't create handler inside thread that has not called Looper.prepare()AlertDialog dialog = builder.create();//设置点击其他地⽅不可取消此 Dialogdialog.setCancelable(false);dialog.setCanceledOnTouchOutside(false);//8.0系统加强后台管理,禁⽌在其他应⽤和窗⼝弹提醒弹窗,如果要弹,必须使⽤TYPE_APPLICATION_OVERLAY,否则弹不出if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {dialog.getWindow().setType((youtParams.TYPE_APPLICATION_OVERLAY));}else {dialog.getWindow().setType((youtParams.TYPE_SYSTEM_ALERT));}dialog.show();}这样,在 " Android低版本 -> Android 6.0 -> Android 8.0 -> 更⾼Android版本" 均可以弹出 Dialog了。
Android弹出菜单的灵活运用(自定义AlertDialog)
lyset2.setOrientation(LinearLayout.HORIZONTAL); LinearLayout lyset3 = new LinearLayout( ComicLivePlayerApp.this); lyset3.setOrientation(LinearLayout.HORIZONTAL); LinearLayout lyset5 = new LinearLayout( ComicLivePlayerApp.this); lyset5.setOrientation(LinearLayout.VERTICAL); lyset1.addView(hcsz1); lyset1.addView(sphcsz); lyset2.addView(zdsz1); lyset2.addView(spzdsz); lyset3.addView(yxsz1); lyset3.addView(spyxsz); // lyset5.addView(lyset1); lyset5.addView(lyset2); lyset5.addView(lyset3); lyset5.setPadding(10, 10, 0, 0); //将lyset5放入弹出框,弹出 new AlertDialog.Builder( ComicLivePlayerApp.this) .setTitle("软件设置") .setView(lyset5) "确定", new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface arg0, int arg1) { icliveSA.Data date = new icliveSA.Data(); date.cacheSetup = (byte) hcsz_set;// 缓冲设置 switch (zdsz_set) { // 振动设置 case 0: // 开 //把布局设进去 .setPositiveButton(
Android继承DialogFragment弹出dialog对话框二-电脑资料
Android继承DialogFragment弹出dialog对话框二-电脑资料之前写过一篇关于Android 继承DialogFragment弹出dialog 对话框一,这次是在上次的基础上修改了一些东西,就是怎样在DialogFragment中获取getDialog()是获取当前对话框句柄,Android 继承DialogFragment弹出dialog对话框二。
就可以进行布局可变的灵活操作。
就像getactivity();一样使用。
下面看代码。
MainActivitypackage com.example.fragmentdialogdemo;import com.example.fragmentdialogdemo.T estDialog.onTestListener;im port android.os.Bundle;import android.support.v4.app.FragmentActivity;importandroid.view.Menu;import android.view.View;import android.view.View.OnClickListener;importandroid.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends FragmentActivity implements OnClickListener,onTestListener {private String mstrName = ;private String mstrHigh = ;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.ac tivity_main);initUI();}private void initUI() {Button buttonTest = (Button)findViewById(R.id.buttonTest);buttonTest.setOnClickListener(this );}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}// 接口回调的函数@Overridepublic void onT estListener(int uniqueIdentifier, String strName,String strHigh) {if(uniqueIdentifier == 1) {Toast.makeText(getApplicationContext(),姓名: + strName + ,身高: + strHigh, Toast.LENGTH_LONG).show();TextView textView1 = (TextView) findViewById(R.id.textView1);textView1.setText(姓名: + strName + ,身高: + strHigh);}mstrName = strName;mstrHigh = strHigh;}@Overridepublic void onClick(View arg0) {switch (arg0.getId()) {case R.id.buttonTest:// 实例化TestDialog,可以传参数进去,例如标题,或者其他参数,还有一个唯一码.TestDialog dialog = new TestDialog().newInstance(请输入, 1,mstrName, mstrHigh);dialog.show(this.getSupportFragmentManager(), TestDialog);break;default:break;}}}TestDialogpackage com.example.fragmentdialogdemo;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;importandroid.content.DialogInterface;importandroid.os.Bundle;importandroid.support.v4.app.DialogFragment;importandroid.view.View;import android.widget.Button;import android.widget.EditText;importandroid.widget.RadioGroup;importandroid.widget.RadioGroup.OnCheckedChangeListener;public class TestDialog extends DialogFragment implements OnCheckedChangeListener{// mUniqueFlag作用是唯一码,可以使返回时做判断private int mUniqueFlag = -1;private onTestListener mOnListener;private EditText meditTextName, meditTextHigh;protected Button mButtonPositive;/** * 新建实例 * * @param title * @param unique * @param strName * @param strHigh * @return */public static TestDialog newInstance(String title, int unique,String strName, String strHigh) {TestDialogtDialog = new TestDialog();Bundle args = new Bundle();args.putString(SelectT emplateTitle,title);args.putInt(MultipleTemplate,unique);args.putString(TemplateName,strName);args.putString(T emplateHigh,strHigh);tDialog.setArguments(args);return tDialog;}public interface onTestListener {/** * * @param uniqueIdentifier * 唯一标识 * @param strName * @param strHigh */public abstractvoid onTestListener(int uniqueIdentifier,String strName, String strHigh);}// 旋转时候保存@Overridepublic void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);outState.putString(InputN ame,meditTextName.getText().toString());outState.putString(InputHigh, meditTextHigh.getText().toString());}@Overridepublic Dialog onCreateDialog(Bundle saveInstanceState) {String title = getArguments().getString(SelectTemplateTitle);mUniqueFlag = getArguments().getInt(MultipleTemplate);AlertDialog.BuilderBuilder = new AlertDialog.Builder(getActivity()).setTitle(title).setPositiveButton(确定, new DialogInterface.OnClickListener() {@Overridepublicvoid onClick(DialogInterface dialog, int which) {// 触发数据回调if (mOnListener != null)mOnListener.onTestListener(mUniqueFlag,meditTextName.g etText().toString(),meditTextHigh.getText().toString());}}).setNegat iveButton(取消, null);// 添加xml布局View view = getActivity().getLayoutInflater().inflate(yout.test_dialog,null);setupUI(view);// 旋转后,恢复数据if (saveInstanceState != null) {String strName = saveInstanceState.getString(InputName);if (strName != null)meditTextName.setT ext(strName);String strHigh= saveInstanceState.getString(InputHigh);if (strHigh != null)meditTextHigh.setText(strHigh);}Builder.setView(view);//创建对话框AlertDialog dialog = (AlertDialog) Builder.create();return dialog;}private void setupUI(View view) {if (view == null)return;RadioGroup radioGroup1 = (RadioGroup)view.findViewById(R.id.radioGroup1);radioGroup1. setOnCheckedChangeListener(this);String strName = getArguments().getString(T emplateName);String strHigh = getArguments().getString(T emplateHigh);meditTextName = (EditText) view.findViewById(R.id.editT extName);meditTextHigh = (EditText)view.findViewById(R.id.editTextHigh);meditTextName.setText(str Name);meditT extHigh.setText(strHigh);}// onAttach是关联activity的,用接口回调@Overridepublic void onAttach(Activity activity) {super.onAttach(activity);try {mOnListener = (onTestListener) activity;} catch (ClassCastException e) {dismiss();}}@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {if (group.getId() == R.id.radioGroup1) {switch (checkedId) {case R.id.radio0://getDialog()是获取当前对话框getDialog().findViewById(youtName).setVisibility(View.VIS IBLE);getDialog().findViewById(youtHigh).setVisibility(Vie w.VISIBLE);break;caseR.id.radio1:getDialog().findViewById(youtName).setVisibili ty(View.GONE);getDialog().findViewById(youtHigh).setVisi bility(View.VISIBLE);break;default:break;}}}}activity_main<li><textview android:gravity="center" android:id="@+id/textView1" android:layout_height="80dp" android:layout_width="match_parent" android:text="点击button"android:textsize="18sp"><b></button></textview></linearlay out>test_dialog<li><radiogroup android:id="@+id/radioGroup1" android:layout_height="wrap_content"android:layout_width="wrap_content"android:orientation="horizontal"><radiobuttonandroid:checked="true" android:id="@+id/radio0" android:layout_height="wrap_content"android:layout_width="wrap_content" android:text="姓名"><radiobutton android:id="@+id/radio1" android:layout_height="wrap_content"android:layout_width="wrap_content" android:text="身高"></radiobutton></radiobutton></radiogroup><li><textview android:gravity="left|center_vertical"android:layout_height="match_parent"android:layout_width="wrap_content" android:text="姓名:" android:textsize="18sp"><edittext android:ems="10" android:id="@+id/editTextName"android:layout_height="wrap_content"android:layout_weight="1"android:layout_width="wrap_content"><requestfocus></reque stfocus></edittext></textview></linearlayout><li><textview android:gravity="left|center_vertical"android:layout_height="match_parent"android:layout_width="wrap_content" android:text="身高:" android:textsize="18sp"><edittext android:ems="10" android:id="@+id/editTextHigh"android:layout_height="wrap_content"android:layout_weight="1"android:layout_width="wrap_content"><requestfocus></reque stfocus></edittext></textview></linearlayout></linearlayout>二、效果看下面动态图三、DialogFragment的部分方法还是那句话多实践,多总结,多交流!期待你的留言,电脑资料《Android 继承DialogFragment弹出dialog对话框二》(https://www.)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Android 适应任何样式提示弹出框Dialog 封装
在Android开发中,难免有各种各样的提示框,如加载数据等待框,删除确认框、输入密码提示框等等,这些是完全可以自定义的,这里给出一个框架以及一个示例,帮助你开发任何样式布局的提示框,废话不多说,直接贴代码:
HintDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.view.KeyEvent;
import android.view.Window;
public class HintDialog
{
Dialog mDialog = null;
private Context mContext = null;
private IHintDialog mIDialogInstance = null;
/**
* 构造函数
* @param context
*/
public HintDialog(Context context)
{
mContext = context;
mDialog = new AlertDialog(mContext)
{
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK &&
mIDialogInstance != null)
{
mIDialogInstance.onKeyDown(keyCode, event);
return true;
}
return super.onKeyDown(keyCode, event);
}
};
mDialog.setCancelable(false);
mDialog.setCanceledOnTouchOutside(false);
}
/**
*
* @param iLayoutResId 此DIALOG采用的布局文件
* @param interfaceInstance 此DIALOG需要实现的一些接口事件 */
public void showDialog(int iLayoutResId, IHintDialog interfaceInstance)
{
if (mDialog == null || iLayoutResId == 0)
{
return;
}
mIDialogInstance = interfaceInstance;
mDialog.show();
mDialog.setContentView(iLayoutResId);
Window window = mDialog.getWindow();
if (mIDialogInstance != null)
{
mIDialogInstance.showWindowDetail(window);
}
}
/**
* 使dialog消失
*/
public void dismissDialog()
{
if (mDialog != null && mDialog.isShowing())
{
mDialog.dismiss();
}
}
/**
* 确定Dialog是否正在显示
* @return
public boolean isShowing()
{
if (mDialog != null && mDialog.isShowing())
{
return mDialog.isShowing();
}
return false;
}
public interface IHintDialog
{
public void onKeyDown(int keyCode, KeyEvent event);
public void showWindowDetail(Window window);
}
}
HintDialogActivity.java
import com.example.hintdialogdemo.HintDialog.IHintDialog;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HintDialogActivity extends Activity implements OnClickListener
{
Button btnConfirm = null;
HintDialog mDialog = null;
@Override
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(yout.activity_hint_dialog);
btnConfirm = (Button) findViewById(R.id.button1);
btnConfirm.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_hint_dialog, menu);
return true;
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.button1:
mDialog = new HintDialog(
HintDialogActivity.this);
mDialog.showDialog(yout.confirm_dialog, new IHintDialog()
{
@Override
public void showWindowDetail(Window window)
{
TextView txvTitle = (TextView) window
.findViewById(R.id.txvTitle);
txvTitle.setText("Confirm?");
Button btnOK = (Button)
window.findViewById(R.id.btnOK);
btnOK.setText("Yes");
btnOK.setOnClickListener(HintDialogActivity.this);
Button btnCancel = (Button) window
.findViewById(R.id.btnCancel);
btnCancel.setText("NO");
btnCancel.setOnClickListener(HintDialogActivity.this);
}
@Override
public void onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
mDialog.dismissDialog();
Toast.makeText(HintDialogActivity.this,
"onKeyback now",
Toast.LENGTH_LONG).show();
}
}
});
break;
case R.id.btnOK:
mDialog.dismissDialog();
Toast.makeText(HintDialogActivity.this,
"Confirm OK now", Toast.LENGTH_LONG).show();
break;
case R.id.btnCancel:
mDialog.dismissDialog();
Toast.makeText(HintDialogActivity.this,
"Confirm Cancel now", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
其实也不难,主要是AlertDialog的使用,注意需要显示调用dissmissDialog()来消失此弹出框。