14+ Android AlertDialog.Builder示例代码和输出
Android
Mike_Dalisay
Software Developer
2人收藏 4132次学习

14+ Android AlertDialog.Builder示例代码和输出

 

    这些Android AlertDialog.Builder样本代码是一些我们使用的任何Android应用程序最常见的UI元素或窗口小部件。一般来说,AlertDialog是出现在你的应用程序前面的小窗口。它让屏幕聚焦,并能接受用户交互。

    对话框通常用于应该中断用户、显示短期任务的通知。

   在这篇文章中,我们将看看我在开发Android系统时经常使用的AlertDialog的类型。我们将介绍如何展现一个Android AlertDialog - 从基础到一点点复杂类型。
我们将涵盖以下内容:
1.0演示视频
2.0如何运行其中一个例子?
3.0 Andr​​oid AlertDialog示例
3.1Andr​​oid AlertDialog与确定按钮
3.2 Andr​​oid AlertDialog与确定和取消按钮
3.3 Andr​​oid AlertDialog与三个按钮
3.4 Andr​​oid AlertDialog与Time Picker
3.5 Andr​​oid AlertDialog与Date Picker
3.6 Andr​​oid AlertDialog与ListView
3.7 Andr​​oid AlertDialog与ScrollView
3.8 Andr​​oid AlertDialog与EditText
3.9 Andr​​oid AlertDialog与WebView
3.10 Andr​​oid AlertDialog与自定义布局
3.11 Andr​​oid AlertDialog与单项选择题
3.12 Andr​​oid AlertDialog与多项选择
3.13 AlertDialog与编辑文本和软键盘的自动显示
3.14持久的AlertDialog
4.0提示和建议
5.0链接与资料
5.1源代码下载
5.2 Andr​​oid AlertDialog在线资源

1.0Android AlertDialog.Builder示例 ---演示视频

 

1.0Android AlertDialog.Builder示例 ---演示视频
首先,我要让你们看到什么将是我们今天代码的最终输出。这里有一个视频演示。

2.0如何运行其中一个示例?

这里是一个用于运行其中一个示例非常简单的代码。

package com.example.alertdialogoneexample;



import android.os.Bundle;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;



public class MainActivity extends Activity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        alertOneButton();



    }



    /*

     * AlertDialog with one action button.

     */

    public void alertOneButton() {



        new AlertDialog.Builder(MainActivity.this)

                .setTitle("One Button")

                .setMessage("Thanks for visiting The Code of a Ninja - codeofaninja.com")

                .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {



                        dialog.cancel();

                    }

                }).show();

    }



}

 

 当你运行上述代码时,将出现这样的画面:

在下面的示例 - 数字3.0至16.0,该显示将是这样的:代码,然后输出。

3.0 Android AlertDialog.Builder示例代码和截图的列表

3.1 Android AlertDialogOK按钮
你总是可以通过改变setPositiveButton的第一个参数来改变按钮的标签,从“OK”到任何你想要的文字或标记。顺便说一下,showToast()是我用于显示给用户的临时的或短期信息提示的另一种方法。

/*
 * AlertDialog with one button.
 */
public void alertOneButton() {

 
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("One Button")
            .setMessage("The Code of a Ninja is your new favorite website.")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    showToast("Thank you!");
                    dialog.cancel();
                }
            }).show();
}

 

输出:

3.2 Android AlertDialog的确定取消例
ninja图标是从项目的绘制资源所使用的操作SetIcon()的图像设置。

/*
 * AlertDialog with two button choices.
 * 
 * We also set the ninja icon here.
 */
public void alertTwoButtons() {
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("Two Buttons")
            .setMessage("Do you think Mike is awesome?")
            .setIcon(R.drawable.ninja)
            .setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("Thank you! You're awesome too!");
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {
                    showToast("Mike is not awesome for you. :(");
                    dialog.cancel();
                }
            }).show();
}

 

输出:

3.3 Android AlertDialog与三个按钮
正如你所看到的,正面的按钮位于左侧,中性的按钮始终在中心,负面的按钮处于右侧。

/*
 * AlertDialog with three button choices.
 * 
 * We also set the ninja icon here.
 */
public void alertThreeButtons() {
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("Three Buttons")
            .setMessage("Where do you want to go?")
            .setIcon(R.drawable.ninja)
            .setPositiveButton("RIGHT",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the RIGHT.");

 
                            dialog.cancel();
                        }
                    })
            .setNeutralButton("CENTER",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the CENTER.");
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("LEFT",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the LEFT.");
                            dialog.cancel();
                        }
                    }).show();
}

 

输出:

3.4 Android AlertDialogTimePicker
在我们的示例中,TimePicker从布局资源虚高。你也可以做到这一点,但我建议使用一个XML布局资源让你的TimePicker可以重复使用。

/*
 * Show AlertDialog with time picker.
 */
public void alertTimePicker() {

 
    /*
     * Inflate the XML view. activity_main is in res/layout/time_picker.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.time_picker, null, false);

 
    // the time picker on the alert dialog, this is how to get the value
    final TimePicker myTimePicker = (TimePicker) view
            .findViewById(R.id.myTimePicker);

 
    /*
     * To remove option for AM/PM, add the following line:
     * 
     * operatingHoursTimePicker.setIs24HourView(true);
     */

 
    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(view)
            .setTitle("Set Time")
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

 
                    String currentHourText = myTimePicker.getCurrentHour()
                            .toString();

 
                    String currentMinuteText = myTimePicker
                            .getCurrentMinute().toString();

 
                    // We cannot get AM/PM value since the returning value
                    // will always be in 24-hour format.

 
                    showToast(currentHourText + ":" + currentMinuteText);

 
                    dialog.cancel();

 
                }

 
            }).show();
}

 

res/layout/time_picker.xml

<?xml version="1.0" encoding="utf-8"?>
<TimePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myTimePicker"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

 
</TimePicker>

 

输出:

3.5 Android AlertDialogDatePicker
要注意的是,我们在这里正在使用一个Datepicker XML布局资源,我们把它叫做date_picker.xml,代码如下:

 

/*
 * Show AlertDialog with date picker.
 */
public void alertDatePicker() {

 
    /*
     * Inflate the XML view. activity_main is in res/layout/date_picker.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.date_picker, null, false);

 
    // the time picker on the alert dialog, this is how to get the value
    final DatePicker myDatePicker = (DatePicker) view.findViewById(R.id.myDatePicker);
    
    // so that the calendar view won't appear
    myDatePicker.setCalendarViewShown(false);
    
    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(view)
            .setTitle("Set Date")
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

 
                    /*
                     * In the docs of the calendar class, January = 0, so we
                     * have to add 1 for getting correct month.
                     * http://goo.gl/9ywsj
                     */
                    int month = myDatePicker.getMonth() + 1;
                    int day = myDatePicker.getDayOfMonth();
                    int year = myDatePicker.getYear();

 
                    showToast(month + "/" + day + "/" + year);

 
                    dialog.cancel();

 
                }

 
            }).show();
}

 res/layout/date_picker.xml code

<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myDatePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

输出:

看起来不怎么好看是吧?上述观点仅适合平板电脑,并不适合手机屏幕,所以我们在使用DatePicker的setCalendarViewShown()方法时,不能使日历运作起来。以下是对于智能手机更好用的东西。

3.6 AlertDialog与简单的ListView
你可以添加或删除里面的CharSequence[]的项目。你可以在if-else语句的帮助下设置在onClick()内的活动。

/*
 * Show AlertDialog with a simple list view.
 * 
 * No XML needed.
 */
public void alertSimpleListView() {

 
    /*
     * WebView is created programatically here.
     * 
     * @Here are the list of items to be shown in the list
     */
    final CharSequence[] items = { "John", "Michael", "Vincent", "Dalisay" };

 
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Make your selection");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

 
            // will toast your selection
            showToast("Name: " + items[item]);
            dialog.dismiss();

 
        }
    }).show();
}

 

3.7 AlertDialogScrollView
    它可以通过使用下面的代码与一个包裹滚动型控件里面一个TextView的一个XML布局资源来实现。下面提供了scroll_text.xml代码。

/*
 * Show AlertDialog with ScrollView.
 * 
 * We use a TextView as ScrollView's child/host
 */
public void alertScrollView() {

 
    /*
     * Inflate the XML view.
     * 
     * @activity_main is in res/layout/scroll_text.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View myScrollView = inflater.inflate(R.layout.scroll_text, null, false);

 
    // textViewWithScroll is the name of our TextView on scroll_text.xml
    TextView tv = (TextView) myScrollView
            .findViewById(R.id.textViewWithScroll);

 
    // Initializing a blank textview so that we can just append a text later
    tv.setText("");

 
    /*
     * Display the text 10 times so that it will exceed the device screen
     * height and be able to scroll
     */
    for (int x = 1; x < 50; x++) {
        tv.append("You've been HACKED!\n");
        tv.append("By NINJAZHAI.\n");
        tv.append("Just kidding.\n\n");
    }

 
    new AlertDialog.Builder(MainActivity.this).setView(myScrollView)
            .setTitle("Scroll View")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }

 
            }).show();

 
}

 

res/layout/scroll_text.xml code

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

 
    <TextView
        android:id="@+id/textViewWithScroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

 
</ScrollView>

 

输出:

3.8 Android AlertDialogEditText等。
我们也虚增一个名为form_elements.xml XML布局资源,代码提供如下。

 

/*
 * Show AlertDialog with some form elements.
 */
public void alertFormElements() {

 
    /*
     * Inflate the XML view. activity_main is in
     * res/layout/form_elements.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View formElementsView = inflater.inflate(R.layout.form_elements,
            null, false);

 
    // You have to list down your form elements
    final CheckBox myCheckBox = (CheckBox) formElementsView
            .findViewById(R.id.myCheckBox);

 
    final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
            .findViewById(R.id.genderRadioGroup);

 
    final EditText nameEditText = (EditText) formElementsView
            .findViewById(R.id.nameEditText);

 
    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(formElementsView)
            .setTitle("Form Elements")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

 
                    String toastString = "";

 
                    /*
                     * Detecting whether the checkbox is checked or not.
                     */
                    if (myCheckBox.isChecked()) {
                        toastString += "Happy is checked!\n";
                    } else {
                        toastString += "Happy IS NOT checked.\n";
                    }

 
                    /*
                     * Getting the value of selected RadioButton.
                     */
                    // get selected radio button from radioGroup
                    int selectedId = genderRadioGroup
                            .getCheckedRadioButtonId();

 
                    // find the radiobutton by returned id
                    RadioButton selectedRadioButton = (RadioButton) formElementsView
                            .findViewById(selectedId);

 
                    toastString += "Selected radio button is: "
                            + selectedRadioButton.getText() + "!\n";

 
                    /*
                     * Getting the value of an EditText.
                     */
                    toastString += "Name is: " + nameEditText.getText()
                            + "!\n";

 
                    showToast(toastString);

 
                    dialog.cancel();
                }

 
            }).show();
}

 

res/layout/form_elements.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

 
    <CheckBox
        android:id="@+id/myCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Happy?" />

 
    <RadioGroup
        android:id="@+id/genderRadioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myCheckBox" >



 
        <RadioButton
            android:id="@+id/maleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="Male" />



 
        <RadioButton
            android:id="@+id/femaleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/maleRadioButton"
            android:text="Female" />

 
    </RadioGroup>

 
    <EditText
        android:id="@+id/nameEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/genderRadioGroup"
        android:ems="10"
        android:hint="Type your name here..." >

 
        <requestFocus />
    </EditText>

 
</RelativeLayout>

 

输出:

3.9 AlertDialogWebView
你可以简单指出WebView的loadURL()方法中的任意网页。

/*
 * Show AlertDialog with web view.
 * 
 * Don't forget the Internet permission on your AndroidManifest.xml
 */
public void alertWebView() {

 
    // WebView is created programatically here.
    WebView myWebView = new WebView(MainActivity.this);
    myWebView.loadUrl("http://google.com/");

 
    /*
     * This part is needed so it won't ask the user to open another browser.
     */
    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

 
    new AlertDialog.Builder(MainActivity.this).setView(myWebView)
            .setTitle("My Web View")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

 
                    dialog.cancel();

 
                }

 
            }).show();
}

 

输出:

3.10 AlertDialog与自定义布局
当你不想AlertDialog看起来那么普通,使用这个。再一次,关键是让你自定义XML资源,然后膨胀它吧!

 

public void alertCustomizedLayout(){
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

 
    // get the layout inflater
    LayoutInflater inflater = MainActivity.this.getLayoutInflater();

 
    // inflate and set the layout for the dialog
    // pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.login, null))
    
    // action buttons
    .setPositiveButton("Login", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // your sign in code here
        }
    })
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // remove the dialog from the screen
        }
    })
    .show();  
    
}

 

res/layout/login.xml

res/layout/login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

 
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="#d1d1d1"
        android:contentDescription="@string/app_name"
        android:scaleType="center"
        android:src="@drawable/ninja" />

 
    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:hint="Username"
        android:inputType="textEmailAddress" />

 
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:fontFamily="sans-serif"
        android:hint="Password"
        android:inputType="textPassword" />

 
</LinearLayout>

 

输出:

3.11 AlertDialog与单项选择
    请注意,我们使用以下setSingleChoiceItems()创建的列表,电台和两个操作按钮。你也可以在三个操作按钮中添加一个中立的按钮。

此外,使用一个字符串资源。 R.array.choices包含在列表中的项目,它可以在strings.xml中找到。如果你想要使用一个array adapter,因为你可以从其他的资源列表,如数据库,得到列表,你可以在我这篇帖子的帮助下使用这个。

 

public void alertSingleChoiceItems(){
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    
    // Set the dialog title
    builder.setTitle("Choose One")
    
    // specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive call backs when items are selected
    // again, R.array.choices were set in the resources res/values/strings.xml
    .setSingleChoiceItems(R.array.choices, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            showToast("Some actions maybe? Selected index: " + arg1);
        }

 
    })
           
     // Set the action buttons
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // user clicked OK, so save the mSelectedItems results somewhere
            // or return them to the component that opened the dialog
            
            int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
            showToast("selectedPosition: " + selectedPosition);
            
        }
    })
    
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the dialog from the screen
            
        }
    })
    
    .show();
    
}

 

res/values/strings.xml

 

<resources>

 
    <string name="app_name">TestApp</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">TestApp</string>
    <string name="showTimeDialogFrom">showTimeDialogFrom</string>

 
    <string-array name="choices">
        <item>Coke</item>
        <item>Pepsi</item>
        <item>Sprite</item>
        <item>Seven Up</item>
    </string-array>

 
</resources>

3.12 AlertDialog与多选项目
    为了给用户机会,从列表中挑选多个项目。
    这一次,我们使用对话框builder’s setMultiChoiceItems()方法,但在列表中的项目仍然是strings.xml中的之一。所述的onClick()方法负责添加或删除被存储在mSelectedItems变量选择的项目。
    顺便说一句,mSelectedItems变量被声明为一个可变MainActivity属性变量。以上AlertDialog可以用下面的代码来实现。

public void alertMultipleChoiceItems(){
    
    // where we will store or remove selected items
    mSelectedItems = new ArrayList<Integer>();  
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    
    // set the dialog title
    builder.setTitle("Choose One or More")
    
    // specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive call backs when items are selected
    // R.array.choices were set in the resources res/values/strings.xml
    .setMultiChoiceItems(R.array.choices, null, new DialogInterface.OnMultiChoiceClickListener() {

 
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            
            if (isChecked) {
                // if the user checked the item, add it to the selected items
                mSelectedItems.add(which);
            } 
        
            else if (mSelectedItems.contains(which)) {
                // else if the item is already in the array, remove it 
                mSelectedItems.remove(Integer.valueOf(which));
            }
            
            // you can also add other codes here, 
            // for example a tool tip that gives user an idea of what he is selecting
            // showToast("Just an example description.");
        }

 
    })
           
     // Set the action buttons
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            
            // user clicked OK, so save the mSelectedItems results somewhere
            // here we are trying to retrieve the selected items indices
            String selectedIndex = "";
            for(Integer i : mSelectedItems){
                selectedIndex += i + ", ";
            }
            
            showToast("Selected index: " + selectedIndex);
        
        }
    })
    
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the AlertDialog in the screen
        }
    })
    
    .show();
    
}

 

在本示例中使用的strings.xml中与上述#11.0相同。

输出:

3.13 AlertDialogEditText和软键盘的自动显示
当你在AlertDialog内有一个EditText,所述的EditText可以集中,但它不会自动显示键盘。用户必须先点击EditText,感觉很恼人。
下面的代码将使得软键盘自动显示。

public void alertEditTextKeyboardShown(){
    
    // creating the EditText widget programatically
    EditText editText = new EditText(MainActivity.this);
    
    // create the AlertDialog as final
    final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
        .setMessage("You are ready to type")
        .setTitle("The Code of a Ninja")
        .setView(editText)
        
         // Set the action buttons
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                
            }
        })
        
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the AlertDialog in the screen
            }
        })
        .create();
    
    // set the focus change listener of the EditText
    // this part will make the soft keyboard automaticall visible
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }
    });
    
    dialog.show();

 
}

 

输出:

3.14当点击一个按钮时,防止AlertDialog关闭
当你的AlertDialog有某种验证时,这是很常用的。在点击一个操作按钮时,它是AlertDialog一个默认的行为。为了防止这种情况,我们必须通过覆盖DialogInterface 让它持续。

下面的代码是非常有效的。

public void alertPersistentDialog(){
     
    final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
        .setTitle("The Code of a Ninja")
        .setMessage("This is a persistent AlertDialog")
        .setPositiveButton("Show Toast", null) // null to override the onClick
        .setNegativeButton("Dismiss", null)
        .setCancelable(false)
        .create();
 
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
 
        @Override
        public void onShow(DialogInterface dialog) {
 
            Button btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            btnPositive.setOnClickListener(new View.OnClickListener() {
 
                @Override
                public void onClick(View view) {
 
                    showToast("Dialog not dismissed!");
                     
                }
            });
             
             
            Button btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            btnNegative.setOnClickListener(new View.OnClickListener() {
 
                @Override
                public void onClick(View view) {
 
                    // dismiss once everything is ok
                    alertDialog.dismiss();
                }
            });
        }
    });
     
    // don't forget to show it
    alertDialog.show();
         
}

输出:

 

4.0提示和建议

    如果你想在Android AlertDialog里添加更多的小工具,你可以夸大它。你可以使用上述代码示例作为您的参考。
   如果你想看到项目的完整代码,我建议您下载整个源代码。在那里,你不仅可以看到MainActivity,而且还有布局资源,字符串资源和AndroidManifest.xml,上述的代码示例只是我们的快速参考。
   如果你想要增加超级棒的Android AlertDialog示例在这份列表中,你可以将其提交到我的电子邮箱:ninjazhai30@gmail.com

5.0链接与文学

5.1源代码下载
  你可以按照上面的全部源代码获取源代码。但是,如果你下载了我们使用的完整的源代码,将其导入不是很方便吗?

  在得到完整的源代码需要一笔小的费用,相比于能带给你的价值、技能提升、职业提升或者你能因此带给你网站或企业的收入是很小的。在有限的时间,我会给你一个低价的源代码。通过点击下面的链接下载源代码。

https://sellfy.com/p/YaQR/

你会得到什么? 在一个项目完整的Android AlertDialog的源代码,一个上述的AlertDialog示例,免费的源代码更新,和来自我提供的免费的电子邮件支持。

5.2 Android AlertDialog网上资源

Android AlertDialog Class

Android Dialogs

Building an AlertDialog from the Official Android Docs

How to create a Dialog without a title?

How to change theme for AlertDialog?

How to show AlertDialog in any position of the screen?

  如果你认为我们错过任何本质的Android AlertDialog.Builder示例,请告诉我们,通过评论!我们希望这个列表是一站式的页面或引用这些示例代码类型的参考。谢谢!

加入1KE学习俱乐部

1KE学习俱乐部是只针对1KE学员开放的私人俱乐部
标签:
安卓