>  기사  >  백엔드 개발  >  Android UI 컨트롤 시리즈: Dialog(대화 상자)

Android UI 컨트롤 시리즈: Dialog(대화 상자)

黄舟
黄舟원래의
2017-01-19 09:37:061411검색

Android에서 대화 상자는 필수입니다. 대화 상자를 사용할 때는 AlertDialog.Builder 클래스를 사용해야 합니다. 물론 시스템의 기본 대화 상자를 처리하는 것 외에도 대화 상자를 사용자 정의할 수도 있습니다. 대화 상자에 버튼이 설정되어 있으면 해당 대화 상자에 대해 OnClickListener 이벤트 모니터링을 수행해야 합니다.

다음은 AlertDialog.Builder 클래스를 사용한 사용자 정의 대화 상자의 예입니다. OK를 클릭하면 사용자 이름과 비밀번호를 입력한 후 로그인 대화 상자로 이동됩니다. 로그인 진행 대화 상자

여기의 사용자 정의 대화 상자는 로그인 대화 상자인 두 개의 TextView와 두 개의 EditText로 구성됩니다. 사용자 정의 대화 상자의 레이아웃 파일은 아래를 참조하세요

또한 AlertDialog를 사용하여 대화 상자를 만들려면 몇 가지 방법을 알아야 합니다.

setTitle() 대화 상자 제목 설정

setIcon( ); 대화상자 아이콘 설정

setMessage(); 대화상자 프롬프트 정보 설정

setItems(); 여러 명령을 표시할 때

setSingleChoiceItems(); 상자에 라디오 선택 목록이 표시됩니다

setMultiChoiceItems() 설정 대화 상자에 일련의 확인란이 표시됩니다

setPositiveButton(); 대화 상자에 "예" 버튼을 추가합니다

setNegativeButton(); 대화 상자에 "아니요" 버튼을 추가합니다
DialogTest.java

package org.hualang.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

public class DialogTest extends Activity {
    /** Called when the activity is first created. */
        ProgressDialog mydialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Dialog dialog=new AlertDialog.Builder(DialogTest.this)
        .setTitle("登录提示")//设置标题
        .setMessage("这里需要登录")//设置对话框显示内容
        .setPositiveButton("确定", //设置确定按钮
        new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                //点击确定转向登录对话框
                                LayoutInflater factory=LayoutInflater.from(DialogTest.this);
                                //得到自定义对话框
                                final View DialogView=factory.inflate(R.layout.dialog, null);
                                //创建对话框
                                AlertDialog dlg=new AlertDialog.Builder(DialogTest.this)
                                .setTitle("登录框")
                                .setView(DialogView)//设置自定义对话框样式
                                .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {//设置监听事件

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                                // 输入完成后点击“确定”开始登录
                                                mydialog=ProgressDialog.show(DialogTest.this, "请稍等...", "正在登录...",true);
                                                new Thread()
                                                {
                                                        public void run()
                                                        {
                                                                try
                                                                {
                                                                        sleep(3000);
                                                                }catch(Exception e)
                                                                {
                                                                        e.printStackTrace();
                                                                }finally
                                                                {
                                                                        //登录结束,取消mydialog对话框
                                                                        mydialog.dismiss();
                                                                }
                                                        }
                                                }.start();
                                        }
                                }).setNegativeButton("取消",//设置取消按钮
                                        new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                        //点击取消后退出程序
                                                        DialogTest.this.finish();

                                                }
                                        }).create();//创建对话框
                                dlg.show();//显示对话框
                        }
                }).setNeutralButton("退出",
                        new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                        // 点击退出后退出程序
                                        DialogTest.this.finish();
                                }
                        }).create();//创建按钮
        //显示对话框
        dialog.show();
    }
}

. 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:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dip"
    android:layout_marginRight="20dip"
    android:text="用户名"
    android:gravity="left"
    android:textAppearance="?android:attr/textAppearanceMedium"
    />
<EditText
        android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium"
/>
<TextView
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:text="密码"
        android:gravity="left"
        android:textAppearance="?android:attr/textAppearanceMedium"
/>
<EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:scrollHorizontally="true"
        android:autoText="false"
        android:capitalize="none"
        android:gravity="fill_horizontal"
        android:password="true"
        android:textAppearance="?android:attr/textAppearanceMedium"

/>
</LinearLayout>

실행 결과는 다음과 같습니다.

Android UI 컨트롤 시리즈: Dialog(대화 상자)

확인을 클릭하면 로그인 대화 상자로 이동합니다. 사용자 정의 대화 상자

Android UI 컨트롤 시리즈: Dialog(대화 상자)

사용자 이름과 비밀번호를 입력한 후 확인을 클릭한 후 진행률 표시줄이 있는 대화 상자를 입력하세요. 시스템 기본값이며 이미 만들어진 컨트롤을 사용합니다. 대화 상자는 3초 후에 종료되고 해당 활동

Android UI 컨트롤 시리즈: Dialog(대화 상자)

보충 콘텐츠:

1. Inflater는 영어로 확장을 의미하고, 안드로이드에서는 확장을 의미합니다.

LayoutInflater의 기능은 findViewById()와 유사합니다. 차이점은 LayoutInflater는 레이아웃 폴더에서 xml 레이아웃 파일을 찾아 인스턴스화하는 데 사용된다는 것입니다! 그리고 findViewById()는 특정 XML(예: Button, TextView 등)에서 특정 위젯 컨트롤을 찾는 것입니다. BaseAdapter의 getView, 뷰의 구성 요소 위젯을 얻기 위한 사용자 정의 대화 상자 등 다양한 위치에서 사용할 수 있습니다.

2. AlertDialog.Builder는 경고 대화 상자를 의미합니다

3. 단위

px: 화면의 픽셀

단위: 인치

mm: 밀리미터

pt: 파운드, 1/72인치

dp: 밀도에 기반한 추상 단위, 160dpi 화면인 경우 1dp=1px

dip : dp와 동일

sp: dp와 유사하지만 사용자의 글꼴 크기 기본 설정에 따라 크기가 조정됩니다.
텍스트 단위는 sp를 사용하는 것이 좋으며, 그렇지 않으면 dip을 사용하는 것이 좋습니다

4. Dialog.xml 설명

①android:layout_marginLeft="20dip"

마진은 side , 위 문장은 컨트롤이 왼쪽에서 20 딥에 있음을 의미합니다. 마찬가지로

android:layout_marginRight="20dip"은 컨트롤이 상위 컨트롤의 오른쪽에서 20dip 떨어져 있음을 의미합니다.
②android:gravity="left": 컨트롤의 텍스트가 표시됨을 나타냅니다. 왼쪽

③android:layout_gravity="center": 컨트롤이 상위 컨트롤의 중앙에 있음을 나타냅니다.

④android:textAppearance의 사용

텍스트(예: TextView EditText RadioButton Button CheckBox 등)를 표시할 수 있으며 때로는 글꼴 크기 제어가 필요합니다. Android 플랫폼은 세 가지 글꼴 크기를 정의합니다.

“?android:attr/textAppearanceLarge”
“?android:attr/textAppearanceMedium”
“?android:attr/textAppearanceSmall”

는 다음과 같이 사용됩니다:

android:textAppearance=”?android:attr/textAppearanceLarge”
android:textAppearance=”?android:attr/textAppearanceMedium”
android:textAppearance=”?android:attr/textAppearanceSmall”

또는

style=”?android:attr/textAppearanceLarge”
style=”?android:attr/textAppearanceMedium”
style=”?android:attr/textAppearanceSmall”

⑤ android:scrollHorizontally="true": 텍스트 설정 Beyond TextView 너비의 경우 가로바 표시 여부

⑥android:autoText="false": 설정한 경우 입력값의 맞춤법 교정을 자동으로 수행합니다. 여기에는 아무런 효과가 없습니다. 입력 방법이 표시되고 입력되면 작동합니다. 여기서 false로 설정하면 부운동에너지가 꺼집니다.

7android:capitalize="none": 영문자의 대문자 표기 방식을 설정합니다. 여기서는 아무런 효과가 없습니다. 입력방법을 팝업으로 띄워야 볼 수 있습니다

8android:password="true": 비밀번호 입력 시 사용되는 작은 점 "."으로 텍스트를 표시합니다

위 내용은 안드로이드 UI 컨트롤 시리즈 Dialog 입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.