Android学习笔记--AlertDialog应用
1. 自定义实现带图标的TextView
IconTextView.java
package com.evor.andtest; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.TextView; public class IconTextView extends TextView { // 命名空间的值 private final String namespace = "http://net.blogjava.mobile"; // 保存图像资源ID的变量 private int resourceId = 0; private Bitmap bitmap; public IconTextView(Context context, AttributeSet attrs) { super(context, attrs); // getAttributeResourceValue方法用来获得组件属性的值,在本例中需要通过该方法的第1个参数指 // 定命名空间的值。该方法的第2个参数表示组件属性名(不包括命名空间名称),第3个参数表示默 // 认值,也就是如果该属性不存在,则返回第3个参数指定的值 resourceId = attrs.getAttributeResourceValue(namespace, "iconSrc", 0); if (resourceId > 0) // 如果成功获得图像资源的ID,装载这个图像资源,并创建Bitmap对象 bitmap = BitmapFactory.decodeResource(getResources(), resourceId); } @Override protected void onDraw(Canvas canvas) { if (bitmap != null) { // 从原图上截取图像的区域,在本例中为整个图像 Rect src = new Rect(); // 将截取的图像复制到bitmap上的目标区域,在本例中与复制区域相同 Rect target = new Rect(); src.left = 0; src.top = 0; src.right = bitmap.getWidth(); src.bottom = bitmap.getHeight(); int textHeight = (int) getTextSize(); target.left = 0; // 计算图像复制到目标区域的纵坐标。由于TextView组件的文本内容并不是 // 从最顶端开始绘制的,因此,需要重新计算绘制图像的纵坐标 target.top = (int) ((getMeasuredHeight() - getTextSize()) / 2) + 1; target.bottom = target.top + textHeight; // 为了保证图像不变形,需要根据图像高度重新计算图像的宽度 target.right = (int) (textHeight * (bitmap.getWidth() / (float) bitmap .getHeight())); // 开始绘制图像 canvas.drawBitmap(bitmap, src, target, getPaint()); // 将TextView中的文本向右移动一定的距离(在本例中移动了图像宽度加2个象素点的位置) canvas.translate(target.right + 2, 0); } super.onDraw(canvas); } }
MainActivity.java (另外还实现了获取系统当前时间的功能)
package com.evor.andtest; import java.text.SimpleDateFormat; import java.util.Date; import android.app.AlertDialog; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends ActionBarActivity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnShowDate = (Button)findViewById(R.id.btnShowDate); Button btnShowTime = (Button)findViewById(R.id.btnShowTime); btnShowDate.setOnClickListener(this); btnShowTime.setOnClickListener(this); } private void showDialog(String title,String msg){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(msg); builder.setPositiveButton("确定", null); builder.create().show(); } public void onClick(View v){ switch(v.getId()){ case R.id.btnShowDate:{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); showDialog("当前日期",sdf.format(new Date())); break; } case R.id.btnShowTime:{ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); showDialog("当前时间",sdf.format(new Date())); break; } } } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:mobile="http://net.blogjava.mobile" xmlns:tools="http://schemas.android.com/tools" 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" android:orientation="vertical" tools:context="com.evor.andtest.MainActivity" > <Button android:id="@+id/btnShowDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示当前日期" /> <Button android:id="@+id/btnShowTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="显示当前时间" /> <com.evor.andtest.IconTextView android:id ="@+id/txtFace1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="测试TextView" mobile:iconSrc="@drawable/ic_launcher" /> <com.evor.andtest.IconTextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="测试TextView" android:textSize="24dp" mobile:iconSrc="@drawable/ic_launcher" /> </LinearLayout>
实现效果:
----------------------------------------------------------------------------------------
2.含有3个按钮的AlertDialog
MainActivity.java
package com.evor.test; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.andtest002alertdialog.R; public class MainActivity extends ActionBarActivity implements OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button)findViewById(R.id.btn1); btn.setOnClickListener(this); } @Override public void onClick(View v) { Builder builder = new AlertDialog.Builder(this); builder.setTitle("是否覆盖文件"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //单击确定按钮后,显示一个无按钮的对话框- new AlertDialog.Builder(MainActivity.this).setMessage("文件已被覆盖").create().show(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 单击取消按钮后,显示一个无按钮的对话框 new AlertDialog.Builder(MainActivity.this).setMessage("取消了操作").create().show(); } }); builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //单击取消按钮后,显示一个无按钮的对话框 new AlertDialog.Builder(MainActivity.this).setMessage("忽略覆盖操作").create().show(); } }).show(); // //以上代码这样写也可以 // new AlertDialog.Builder(this) // .setTitle("是否覆盖文件") // .setPositiveButton("确定", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // //单击确定按钮后,显示一个无按钮的对话框- // new AlertDialog.Builder(MainActivity.this).setMessage("文件已被覆盖").create().show(); // } // }) // .setNegativeButton("取消", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // 单击取消按钮后,显示一个无按钮的对话框 // new AlertDialog.Builder(MainActivity.this).setMessage("取消了操作").create().show(); // // } // }) // .setNeutralButton("忽略", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // //单击取消按钮后,显示一个无按钮的对话框 // new AlertDialog.Builder(MainActivity.this).setMessage("忽略覆盖操作").create().show(); // // } // }).show(); } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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" android:orientation="vertical" tools:context="com.evor.test.MainActivity" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="确认/取消对话框" /> </LinearLayout>
实现效果:
----------------------------------------------------------------------------------------
3.用AlertDialog实现单选框、多选框
MainActivity.java
package com.evor.test; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; public class MainActivity extends ActionBarActivity implements OnClickListener{ //列表对话框的字符串数组数据源 private String[] provinces = new String[]{ "辽宁省","山东省","河北省","福建省","广东省","黑龙江省" }; //单击事件类的对象实例 private ButtonOnClick buttonOnClick = new ButtonOnClick(1); //用于保存多选列表对话框中的ListView对象 private ListView listView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = (Button)findViewById(R.id.btn1); Button btn2 = (Button)findViewById(R.id.btn2); Button btn3 = (Button)findViewById(R.id.btn3); btn1.setOnClickListener(this); btn2.setOnClickListener(this); btn3.setOnClickListener(this); } //显示简单列表对话框 private void showListDialog(){ new AlertDialog.Builder(this).setTitle("选择省份") .setItems(provinces,new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final AlertDialog ad = new AlertDialog.Builder(MainActivity.this) .setMessage("您已经选择了:"+which+":"+provinces[which]).show(); Handler handler = new Handler(); //设置定时器,5S后调用run方法,使对话框自动消失 handler.postDelayed(new Runnable(){ @Override public void run() { ad.dismiss(); } }, 5000); } }).show(); } //显示单选列表对话框 private void showSingleChoiceDialog(){ new AlertDialog.Builder(this).setTitle("选择省份") .setSingleChoiceItems(provinces, 1, buttonOnClick) .setPositiveButton("确定",buttonOnClick) .setNegativeButton("取消", buttonOnClick).show(); } //显示多选列表对话框(演示了另一种创建对话框的方法) private void showMultiChoseDialog(){ Builder builder = new AlertDialog.Builder(this); builder.setTitle("选择省份"); //设置选项 builder.setMultiChoiceItems(provinces, new boolean[]{false,false,false,false,false,false}, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { } }); //设置确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //int count = listView.getCount(); String s = "您选择了:"; for(int i = 0 ;i < provinces.length ; i++){ if(listView.getCheckedItemPositions().get(i)==true) s= s + i+":"+listView.getAdapter().getItem(i); } if(listView.getCheckedItemPositions().size()>0){ new AlertDialog.Builder(MainActivity.this).setMessage(s).show(); }else{ new AlertDialog.Builder(MainActivity.this).setMessage("未选择任何省份").show(); } } }); //设置取消按钮 builder.setNegativeButton("取消", null); //创建对话框 AlertDialog ad = builder.create(); listView = ad.getListView(); ad.show(); } //确定对话框内选择的是什么 private class ButtonOnClick implements DialogInterface.OnClickListener{ private int index; //表示省份数组的索引 public ButtonOnClick(int index){ this.index = index; } @Override public void onClick(DialogInterface dialog, int which) { //which表示单击的按钮索引,所有列表项的索引都是大于等于0的,按钮的索引是小于0的 if(which >=0){ index = which; //如果单击的是列表项,保存列表项索引到index //如果想单击之后关闭对话框,可调用dialog.cancel()或者dialog.dismiss() }else{ if(which == DialogInterface.BUTTON_POSITIVE){ //单击确定按钮 new AlertDialog.Builder(MainActivity.this) .setMessage("选择了"+index+":"+provinces[index]).show(); } } } }//END CLASS //响应按钮动作 @Override public void onClick(View v) { switch(v.getId()){ case R.id.btn1:{ showListDialog(); break; } case R.id.btn2:{ showSingleChoiceDialog(); break; } case R.id.btn3:{ showMultiChoseDialog(); break; } } } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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" android:orientation="vertical" tools:context="com.evor.test.MainActivity" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示列表对话框" /> <Button android:id="@+id/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示单选列表对话框" /> <Button android:id="@+id/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示多选列表对话框" /> </LinearLayout>
----------------------------------------------------------------------------------------
4.用AlertDialog实现含编辑框的对话框
MainActivity.java
package com.evor.test; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TableLayout; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { final Builder builder = new AlertDialog.Builder(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = (Button)findViewById(R.id.btn1); btn1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { builder.setTitle("含编辑框的对话框"); TableLayout loginForm = (TableLayout)getLayoutInflater().inflate(R.layout.login, null); builder.setView(loginForm); //设置对话框显示的view对象 builder.setPositiveButton("登录", new DialogInterface.OnClickListener(){ //注意,要加前面的DialogInterface,否则会混淆 @Override public void onClick(DialogInterface dialog,int which) { //执行登录处理 } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 取消登录 } }); builder.create().show(); }; }); }//END onCreate }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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" android:orientation="vertical" tools:context="com.evor.test.MainActivity" > <Button android:id="@+id/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="输入信息" /> </LinearLayout>
login.xml
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/loginForm" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TableRow> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="用户名" android:textSize="10pt" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请填写登录账号" android:selectAllOnFocus="true" /> </TableRow> <TableRow> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="密码" android:textSize="10pt" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:password="true" /> </TableRow> <TableRow> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="电话" android:textSize="10pt" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请输入电话号码" /> </TableRow> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="注册" /> </TableLayout>
实现效果:
----------------------------------------------------------------------------------------
5.AlertDialog作为Activity的主题
MainActivity.java
package com.evor.test; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { private DateDialog dateDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnCurrentDate = (Button) findViewById(R.id.btn1); Button btnFinish = (Button) findViewById(R.id.btn2); MyOnClickListener mylistener = new MyOnClickListener(); btnCurrentDate.setOnClickListener(mylistener); btnFinish.setOnClickListener(mylistener); dateDialog = new DateDialog(this); }// END onCreate class MyOnClickListener implements View.OnClickListener { @Override public void onClick(View v) { switch(v.getId()){ case R.id.btn1:{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()); dateDialog.setTitle("当前日期:"+sdf.format(new Date())); dateDialog.setButton("确定", new OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { } }); dateDialog.setOnDismissListener(new OnDismissListener(){ @Override public void onDismiss(DialogInterface dialog) { new DateDialog.Builder(MainActivity.this).create().show(); } }); dateDialog.show(); break; } case R.id.btn2: finish(); break; } }//END onClick }//END inner class @Override public boolean onTouchEvent(MotionEvent event){ finish(); return true; } }
DateDialog.java
package com.evor.test; import android.app.AlertDialog; import android.content.Context; import android.view.MotionEvent; public class DateDialog extends AlertDialog{ public DateDialog(Context context){ super(context); } //触摸屏幕任何地方都会出发该事件 @Override public boolean onTouchEvent(MotionEvent event){ dismiss(); //关闭对话框 return super.onTouchEvent(event); } }
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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" android:orientation="horizontal" tools:context="com.evor.test.MainActivity" > <Button android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="当前日期" /> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="关闭" /> </LinearLayout>
AndroidManifest.xml中需要修改的地方
<activity android:name="com.evor.test.MainActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Dialog"> <!-- 设置主题为对话框形式 --> 。。。。。省略 </activity>
上面加了一行 android:theme="@android:style/Theme.Dialog"
实现效果:
------------------------------------------------