- 浏览: 676212 次
文章分类
最新评论
-
ymm8505:
不错…… 学习了
final -
zht19880706:
楼主,没看懂在 android 代码怎么设置
Android Audio延迟(latency) -
zjc198805:
用popwindow呈现的时候,好像不能会弹,不知道怎么回事, ...
android pinch:双指缩放图片和单指拖拽
android-Alertdialog用法
一个对话框一般是一个出现在当前Activity之上的一个小窗口. 处于下面的Activity失去焦点, 对话框接受所有的用户交互. 对话框一般用于提示信息和与当前应用程序直接相关的小功能.
Android API 支持下列类型的对话框对象:
警告对话框 AlertDialog: 一个可以有0到3个按钮, 一个单选框或复选框的列表的对话框. 警告对话框可以创建大多数的交互界面, 是推荐的类型.
进度对话框 ProgressDialog: 显示一个进度环或者一个进度条. 由于它是AlertDialog的扩展, 所以它也支持按钮.
日期选择对话框 DatePickerDialog: 让用户选择一个日期.
时间选择对话框 TimePickerDialog: 让用户选择一个时间.
如果你希望自定义你的对话框, 可以扩展Dialog类.
Showing a Dialog 显示对话框
一个对话框总是被创建和显示为一个Activity的一部分. 你应该在Activity的onCreateDialog(int)中创建对话框. 当你使用这个回调函数时,Android系统自动管理每个对话框的状态并将它们和Activity连接, 将Activity变为对话框的"所有者". 这样,每个对话框从Activity继承一些属性. 例如,当一个对话框打开时, MENU键会显示Activity的菜单, 音量键会调整Activity当前使用的音频流的音量.
注意: 如果你希望在onCreateDialog()方法之外创建对话框, 它将不会依附在Activity上. 你可以使用setOwnerActivity(Activity)来将它依附在Activity上.
当你希望显示一个对话框时, 调用showDialog(int)并将对话框的id传给它.
当一个对话框第一次被请求时,Android调用onCreateDialog(int). 这里是你初始化对话框的地方. 这个回调函数传入的id和showDialog(int)相同. 创建对话框之后,将返回被创建的对象.
在对话框被显示之前,Android还会调用onPrepareDialog(int, Dialog). 如果你希望每次显示对话框时有动态更改的内容, 那么就改写这个函数. 该函数在每次一个对话框打开时都调用. 如果你不定义该函数,则对话框每次打开都是一样的. 该函数也会传入对话框的id以及你在onCreateDialog()中创建的Dialog对象.
最好的定义onCreateDialog(int) 和onPrepareDialog(int, Dialog) 的方法就是使用一个switch语句来检查传入的id. 每个case创建相应的对话框. 例如, 一个游戏使用两个对话框: 一个来指示游戏暂停,另一个指示游戏结束. 首先, 为它们定义ID:static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1;
然后, 在onCreateDialog(int)中加入一个switch语句:
- protectedDialogonCreateDialog(intid){
- Dialogdialog;
- switch(id){
- caseDIALOG_PAUSED_ID:
- //dotheworktodefinethepauseDialog
- break;
- caseDIALOG_GAMEOVER_ID:
- //dotheworktodefinethegameoverDialog
- break;
- default:
- dialog=null;
- }
- returndialog;
- }
在需要显示对话框是, 调用showDialog(int), 传入对话框的id:
showDialog(DIALOG_PAUSED_ID);Dismissing a Dialog 解除对话框
当你准备关闭对话框时, 你可以使用dismiss()函数. 如果需要的话, 你也可以从Activity调用dismissDialog(int), 二者效果是一样的.
如果你使用onCreateDialog(int)来管理你的对话框的状态, 那么每次你的对话框被解除时, 该对话框对象的状态会被Activity保存. 如果你决定你不再需要这个对象或者需要清除对话框的状态, 那么你应该调用 removeDialog(int). 这将把所有该对象的内部引用移除, 如果该对话框在显示的话将被解除.
Using dismiss listeners 使用解除监听器
如果你希望在对话框解除时运行某些程序, 那么你应该给对话框附加一个解除监听器.
首先定义DialogInterface.OnDismissListener接口. 这个接口只有一个方法, onDismiss(DialogInterface), 该方法将在对话框解除时被调用.
然后将你的OnDismissListener实现传给setOnDismissListener().
然而,注意对话框也可以被"取消". 这是一个特殊的情形, 它意味着对话框被用户显式的取消掉. 这将在用户按下"back"键时, 或者对话框显式的调用cancel()(按下对话框的cancel按钮)时发生. 当一个对话框被取消时, OnDismissListener将仍然被通知, 但如果你希望在对话框被显示取消(而不是正常解除)时被通知, 则你应该使用setOnCancelListener()注册一个DialogInterface.OnCancelListener.
Creating an AlertDialog 创建警告对话框
An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:
一个警告对话框是对话框的一个扩展. 它能够创建大多数对话框用户界面并且是推荐的对话框类新星. 对于需要下列任何特性的对话框,你都应该使用它:
一个标题
一条文字消息
1个-3个按钮
一个可选择的列表(单选框或者复选框)
要创建一个AlertDialog, 使用AlertDialog.Builder子类. 使用AlertDialog.Builder(Context)来得到一个Builder, 然后使用该类的公有方法来定义AlertDialog的属性. 设定好以后, 使用create()方法来获得AlertDialog对象.
下面的主题展示了如何为AlertDialog定义不同的属性, 使用AlertDialog.Builder类. 如果你使用这些示例代码, 你可以在onCreateDialog()中返回最后的Dialog对象来获得图片中对话框的效果.
Adding buttons 增加按钮
- AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
- builder.setMessage("Areyousureyouwanttoexit?")
- .setCancelable(false)
- .setPositiveButton("Yes",newDialogInterface.OnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intid){
- MyActivity.this.finish();
- }
- })
- .setNegativeButton("No",newDialogInterface.OnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intid){
- dialog.cancel();
- }
- });
- AlertDialogalert=builder.create();
注意:对每种按钮类型,只能为AlertDialog创建一个。也就是说,一个AlertDialog不能有两个以上的"positive"按钮。这使得可能的按钮数量最多为三个:肯定、否定、中性。这些名字和实际功能没有联系,但是将帮助你记忆它们各做什么事情。
- finalCharSequence[]items={"Red","Green","Blue"};
- AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
- builder.setTitle("Pickacolor");
- builder.setItems(items,newDialogInterface.OnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intitem){
- Toast.makeText(getApplicationContext(),items[item],Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialogalert=builder.create();
Adding checkboxes and radio buttons 增加单选框和复选框
注意: 要在你的acitivity离开和暂停时保存选择, 你必须在activity的声明周期中正确的保存和恢复设置。为了永久性保存选择,你必须使用数据存储技术中的一种。
要创建一个具有单选列表的AlertDialog,只需将一个例子中的setItems()换成 setSingleChoiceItems():
- finalCharSequence[]items={"Red","Green","Blue"};
- AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
- builder.setTitle("Pickacolor");
- builder.setSingleChoiceItems(items,-1,newDialogInterface.OnClickListener(){
- publicvoidonClick(DialogInterfacedialog,intitem){
- Toast.makeText(getApplicationContext(),items[item],Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialogalert=builder.create();
Creating a ProgressDialog 创建进度对话框
打开一个进度对话框很简单,只需要调用 ProgressDialog.show()即可。例如,上图的对话框可以不通过onCreateDialog(int),而直接显示:
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
第一个参数是应用程序上下文。第二个为对话框的标题(这里为空),第三个为对话框内容, 最后一个为该进度是否为不可确定的(这只跟进度条的创建有关,见下一节)。
进度对话框的默认样式为一个旋转的环。如果你希望显示进度值,请看下一节。
Showing a progress bar 显示进度条
使用一个动画进度条来显示进度:
使用 ProgressDialog(Context)构造函数来初始化一个ProgressDialog对象。
将进度样式设置为"STYLE_HORIZONTAL",使用setProgressStyle(int)方法。并且设置其它属性,例如内容等。
在需要显示时调用show()或者从onCreateDialog(int)回调函数中返回该ProgressDialog。
你可以使用 setProgress(int)或者incrementProgressBy(int)来增加显示的进度。
例如,你的设置可能像这样:ProgressDialog progressDialog;
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
设置很简单。大部分创建进度对话框需要的代码是在更新它的进程中。你可能需要在一个新的线程中更新它,并使用Handler来将进度报告给Activity。如果你不熟悉使用Handler和另外的线程,请看下列例子,该例子使用了一个新的线程来更新进度。
Example ProgressDialog with a second thread 例--使用一个线程来显示进度对话框
这个例子使用一个线程来跟踪一个进程的进度(其实为从1数到100)。每当进度更新时,该线程通过Handler给主activity发送一个消息。主Activity更新ProgressDialog.package com.example.progressdialog;
- importandroid.app.Activity;
- importandroid.app.Dialog;
- importandroid.app.ProgressDialog;
- importandroid.os.Bundle;
- importandroid.os.Handler;
- importandroid.os.Message;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- publicclassNotificationTestextendsActivity{
- staticfinalintPROGRESS_DIALOG=0;
- Buttonbutton;
- ProgressThreadprogressThread;
- ProgressDialogprogressDialog;
- /**Calledwhentheactivityisfirstcreated.*/
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //Setupthebuttonthatstartstheprogressdialog
- button=(Button)findViewById(R.id.progressDialog);
- button.setOnClickListener(newOnClickListener(){
- publicvoidonClick(Viewv){
- showDialog(PROGRESS_DIALOG);
- }
- });
- }
- protectedDialogonCreateDialog(intid){
- switch(id){
- casePROGRESS_DIALOG:
- progressDialog=newProgressDialog(NotificationTest.this);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- progressDialog.setMessage("Loading...");
- progressThread=newProgressThread(handler);
- progressThread.start();
- returnprogressDialog;
- default:
- returnnull;
- }
- }
- //DefinetheHandlerthatreceivesmessagesfromthethreadandupdatetheprogress
- finalHandlerhandler=newHandler(){
- publicvoidhandleMessage(Messagemsg){
- inttotal=msg.getData().getInt("total");
- progressDialog.setProgress(total);
- if(total>=100){
- dismissDialog(PROGRESS_DIALOG);
- progressThread.setState(ProgressThread.STATE_DONE);
- }
- }
- };
- /**Nestedclassthatperformsprogresscalculations(counting)*/
- privateclassProgressThreadextendsThread{
- HandlermHandler;
- finalstaticintSTATE_DONE=0;
- finalstaticintSTATE_RUNNING=1;
- intmState;
- inttotal;
- ProgressThread(Handlerh){
- mHandler=h;
- }
- publicvoidrun(){
- mState=STATE_RUNNING;
- total=0;
- while(mState==STATE_RUNNING){
- try{
- Thread.sleep(100);
- }catch(InterruptedExceptione){
- Log.e("ERROR","ThreadInterrupted");
- }
- Messagemsg=mHandler.obtainMessage();
- Bundleb=newBundle();
- b.putInt("total",total);
- msg.setData(b);
- mHandler.sendMessage(msg);
- total++;
- }
- }
- /*setsthecurrentstateforthethread,
- *usedtostopthethread*/
- publicvoidsetState(intstate){
- mState=state;
- }
- }
- }
例如,创建如图所示的对话框:
创建一个xml布局custom_dialog.xml:
- http://schemas.android.com/apk/res/android"
- android:id="@+id/layout_root"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- >
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp"
- />
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:textColor="#FFF"
- />
将以上布局设为对话框的content view,并且定义ImageView 和 TextView的内容:
- ContextmContext=getApplicationContext();
- Dialogdialog=newDialog(mContext);
- dialog.setContentView(R.layout.custom_dialog);
- dialog.setTitle("CustomDialog");
- TextViewtext=(TextView)dialog.findViewById(R.id.text);
- text.setText("Hello,thisisacustomdialog!");
- ImageViewimage=(ImageView)dialog.findViewById(R.id.image);
- image.setImageResource(R.drawable.android);
使用前面所讲的方法显示对话框。
一个使用Dialog类建立的对话框必须有一个标题。如果你不调用setTitle(),那么标题区域会保留空白。如果你不希望有一个标题,那么你应该使用AlertDialog类来创建自定义对话框。然而,由于一个AlertDialog使用AlertDialog.Builder类来建立最方便,所以你没有方法使用setContentView(int),而是只能使用setView(View)。该方法接受一个View对象,所以你需要从xml中展开你的根View。
要展开一个xml布局,使用 getLayoutInflater() (或 getSystemService())取得LayoutInflater,然后调用inflate(int, ViewGroup),第一个参数为布局id,而第二个参数为根view的id。现在,你可以使用展开后的布局来找到View对象并定义ImageView和TextView元素的内容。然后实例化AlertDialog.Builder并使用setView(View)来为对话框设置展开后的布局。例如:
- AlertDialog.Builderbuilder;
- AlertDialogalertDialog;
- ContextmContext=getApplicationContext();
- LayoutInflaterinflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
- Viewlayout=inflater.inflate(R.layout.custom_dialog,
- (ViewGroup)findViewById(R.id.layout_root));
- TextViewtext=(TextView)layout.findViewById(R.id.text);
- text.setText("Hello,thisisacustomdialog!");
- ImageViewimage=(ImageView)layout.findViewById(R.id.image);
- image.setImageResource(R.drawable.android);
- builder=newAlertDialog.Builder(mContext);
- builder.setView(layout);
- alertDialog=builder.create();
1. Context.public abstract Object getSystemService (String name):Return the handle to a system-level service by name.The class of the returned object varies by the requested name. 具体参见文档。
2. 2种获得LayoutInflater的方法
(1)通过SystemService获得
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
(2)从给定的context中获取
(3)二者区别:实质是一样的,请看源码
- publicstaticLayoutInflaterfrom(Contextcontext){
- LayoutInflaterLayoutInflater=
- (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- if(LayoutInflater==null){
- thrownewAssertionError("LayoutInflaternotfound.");
- }
- returnLayoutInflater;
- }
3. LayoutInflater.inflate()
将Layout文件转换为View,顾名思义,专门供Layout使用的Inflater。虽然Layout也是View的子类,但在android中如果想将xml中的Layout转换为View放入.java代码中操作,只能通过Inflater,而不能通过findViewById(),这一段描述有误,看如下代码。看下面文档写的已经很清楚。
- <ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- <LinearLayoutandroid:id="@+id/placeslist_linearlayout"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- </LinearLayout>
- </ScrollView>
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.placeslist_linearlayout);
linearLayout.addView(place_type_text);
这是可运行的,这上面的xml中,LinearLayout不再是Layout的代表,而只是一个普通的View。
4. findViewById有2中形式
R.layout.xx 是引用res/layout/xx.xml的布局文件(inflate方法),R.id.xx是引用布局文件里面的组件,组件的id是xx...(findViewById方法)。看看R.java配置文件吧,R对文件分类管理,多写几个layout.xml后你会发现,所有的组件id都能用R.id.xx来查看,但是组件不在setContentView()里面的layout中就无法使用,Activity.findViewById()会出现空指针异常。
(1)Activity中的findViewById()
(2)View中的findViewById()
5.
相关推荐
NULL 博文链接:https://2528.iteye.com/blog/1123944
android 使用alertdialog创建自定义对话框
最近项目里有个功能点,需要使用...我需要继承AlertDialog,设置自己的内容view,重写onKeyDown方法,设置dialog的位置等...... 写了个demo. Demo是在5.0手机上测试的, 6.0以上系统还需要添加动态运行时权限的逻辑 。
主要介绍了Android中AlertDialog用法,结合实例形式简单分析了AlertDialog的基本调用与功能实现技巧,需要的朋友可以参考下
一次性警报对话框Android AlertDialog 对于给定的字符串只显示一次。 这是AlertDialog的子类,支持其所有功能。 唯一的区别是在其初始化中提供了一个键,用于检查默认的 SharedPreferences 并在显示后保存自身。用例...
主要为大家详细介绍了Android使用AlertDialog创建对话框的方法料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
主要为大家详细介绍了android AlertDialog多种使用方法,包括普通对话框、单选对话框、多选对话框等,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
主要使用了AlertDialog、ActionSheetDialog来实现,AlertDialog的方法和android中自带的用法相似,ActionSheetDialo的用法和AlertDialog差不多,基本的使用思路是:获取Dialog布局、获取自定义Dialog布局中的控件、...
最近项目里有个功能点,需要使用定制seekbar调节媒体音量,不能使用【按物理音量上下键】弹出的系统dialog做...我需要继承AlertDialog,设置自己的内容view,重写onKeyDown方法,设置dialog的位置等...... 写了个demo
spots-dialog, 带有移动点进度指示器的Android AlertDialog 点进度对话框 Android AlertDialog随移动点进度指示器打包为Android库。 ========== =用法可以在 Maven 中央仓库中使用的库。 你可以使用以下方法获取它:...
很好的入门资料,建议初学者照着写一遍,效果会很好的。
当然,这也是不失为一个不错的解决方式,但是一般的情况却是这样,我们重写的对话框,也许只在一个特定的地方会用到,为了这一次的使用,而去创建一个新类,往往有点杀鸡用牛刀的感觉,甚至会对我们的程序增加不必要...
主要介绍了Android中AlertDialog各种对话框的用法在项目开发中经常用的到,本文给大家介绍的非常详细,具有参考借鉴价值
本文实例讲述了Android AlertDialog对话框用法。分享给大家供大家参考,具体如下: AlertDialog对话框的介绍 1、获得AlertDialog静态内部类Buidler对象,由该类来创建AlertDialog对象,因为AlertDialog的构造方法全部...
主要介绍了Android入门之AlertDialog用法,对Android初学者有很多的借鉴学习之处,需要的朋友可以参考下
使用AlertDialog.Builder创建对话框时,可以使用builder.setNegativeButton和builder.setPositiveButton两个方法设置取消按钮和确认按钮的点击事件。然而问题在于,只要用户点击了确认按钮或者取消按钮
一个含有listview,cardview,sqlite,barcode,qrcode,alertdialog的基本用法的小项目