【Android学习】之AlertDialog的使用

此实例为Android从入门到精通 第四章习题第三题。


编写Android程序,应用AlertDialog实现自定义的登录对话框。


效果:

【Android学习】之AlertDialog的使用_第1张图片

单独创建一个布局文件,来显示登录界面:

如图:【Android学习】之AlertDialog的使用_第2张图片

代码:

<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:id="@+id/tableLayout1"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:gravity="center_vertical"
	android:stretchColumns="0,3"	
	>
	<!-- 第一行 -->
	<TableRow android:id="@+id/tableRow1" 
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
		<TextView/>
		<TextView android:text="用户名:" 
			android:id="@+id/textView1" 
			android:layout_width="wrap_content"
			android:textSize="24px" 
			android:layout_height="wrap_content"
			/>
		<EditText android:id="@+id/editText1" 
			android:textSize="24px" 
			android:layout_width="wrap_content" 
			android:layout_height="wrap_content" android:minWidth="200px"/>
		<TextView />
	</TableRow>
	<!-- 第二行 -->	
	<TableRow android:id="@+id/tableRow2" 
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
		<TextView/>
		<TextView android:text="密    码:" 
			android:id="@+id/textView2" 
			android:textSize="24px" 
			android:layout_width="wrap_content" 
			android:layout_height="wrap_content"/>
		<EditText android:layout_height="wrap_content" 
			android:layout_width="wrap_content" 
			android:textSize="24px" 
			android:id="@+id/editText2" 
			android:inputType="textPassword"/>
		<TextView />
	</TableRow>
</TableLayout>



在OnCreate函数里添加代码:

                                Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setIcon(R.drawable.advise); // 设置对话框的图标
				builder.setTitle("用户登录:"); // 设置对话框的标题
				LayoutInflater inflater=getLayoutInflater();
				View view=inflater.inflate(R.layout.login, null);
				builder.setView(view);
				builder.setPositiveButton("登录", null);								//添加确定按钮
				builder.setNegativeButton("退出", null);								//添加取消按钮
				builder.create().show(); // 创建对话框并显示

在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。
具体作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

你可能感兴趣的:(【Android学习】之AlertDialog的使用)