|
有時候AlertDialog上的按鈕,文本並不能滿足我們程序的要求,比如說我們要設計個登錄窗口,如果用上文的方法是沒法插入EditText的,也就無法實現。其實AlertDialog是可以顯示View的,這樣的話,幾乎任何元素都可以在AlertDialog中顯示。
先看效果圖:
下面我們用代碼一步一步實現。
先講思路,首先寫個view的XML文件,把登錄框的提示以用輸入框寫進去,然後把xml文件轉成View類型,再用setView()即可。 下面是我寫好的xml文件,文件名為login.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView android:text="用户名"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dip"
- android:textSize="25px"
- />
- <EditText android:id="@+id/usr"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_margin="10dip"
- />
- <TextView android:text="密码"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginLeft="10dip"
- android:textSize="25px"
- />
- <EditText android:id="@+id/pwd"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_margin="10dip"
- />
複製代碼
接下來是程序代碼:
- package com.pocketdigi.test;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class main extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button button=(Button)findViewById(R.id.b1);
- button.setOnClickListener(openDialog);
- }
- private OnClickListener openDialog=new OnClickListener(){
- @Override
- public void onClick(View v) {
- Login();//点击执行弹出登录对话框
- }
- };
- public void Login() {
- LayoutInflater factory=LayoutInflater.from(main.this);
- final View v1=factory.inflate(R.layout.login,null);
- //R.layout.login与login.xml文件名对应,把login转化成View类型
- AlertDialog.Builder dialog=new AlertDialog.Builder(main.this);
- dialog.setTitle("用户登录");
- dialog.setView(v1);//设置使用View
- //设置控件应该用v1.findViewById 否则出错
- dialog.setPositiveButton("登录", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- //登录代码
- }
- });
- dialog.setNegativeButton("取消",new DialogInterface.OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
- // TODO Auto-generated method stub
-
- }
- });
- dialog.show();
- }
- }
複製代碼
文章出處 |
|