Summary of 8 Android Dialog usage methods

Keywords: Android xml

Author: @ gzdaijie
This article is original by the author. Please indicate the source of Reprint: https://www.cnblogs.com/gzdaijie/p/5222191.html

Catalog

1. Write in front
2. Code example
2.1 General Dialog (Figure 1 and Figure 2)
2.2 list Dialog (Figure 3)
2.3 radio Dialog (Figure 4)
2.4 multi select Dialog (Figure 5)
2.5 wait for Dialog (Figure 6)
2.6 progress bar Dialog (Figure 7)
2.7 edit Dialog (Figure 8)
2.8 custom Dialog (Figure 9)
3. Copy callback function

1. Write in front
Android provides a wealth of Dialog functions. This article introduces the most commonly used 8 kinds of Dialog usage methods, including common (including prompt messages and buttons), list, radio selection, multiple selection, waiting, progress bar, editing, customization and other forms, which will be introduced in part 2.
Sometimes, we want to complete some specific functions when the Dialog is created or closed. This requires copying Dialog's create(), show(), dispatch(), and other methods, which will be described in part 3.
2. Code example
Picture example

2.1 General Dialog (Figure 1 and Figure 2)
2 buttons

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonNormal = (Button) findViewById(R.id.button_normal);
        buttonNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog();
            }
        });
    }

    private void showNormalDialog(){
        /* @setIcon Settings dialog Icon
         * @setTitle Set dialog title
         * @setMessage Set dialog message prompt
         * setXXX Method returns a Dialog object, so properties can be chained
         */
        final AlertDialog.Builder normalDialog = 
            new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle("I am an ordinary Dialog")
        normalDialog.setMessage("Which button do you want to click?");
        normalDialog.setPositiveButton("Determine", 
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        normalDialog.setNegativeButton("Close", 
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        // display
        normalDialog.show();
    }
}

3 buttons

/* @setNeutralButton Set middle button
 * If you only need one button, just set the set positive button
 */
private void showMultiBtnDialog(){
    AlertDialog.Builder normalDialog = 
        new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("I am an ordinary Dialog").setMessage("Which button do you want to click?");
    normalDialog.setPositiveButton("Button 1", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNeutralButton("Button 2", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNegativeButton("Button 3", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    // Create an instance and display
    normalDialog.show();
}

2.2 list Dialog (Figure 3)

private void showListDialog() {
    final String[] items = { "I'm 1","I'm 2","I'm 3","I'm 4" };
    AlertDialog.Builder listDialog = 
        new AlertDialog.Builder(MainActivity.this);
    listDialog.setTitle("I'm a list Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // which subscript starts from 0
            // ...To-do
            Toast.makeText(MainActivity.this, 
                "You clicked" + items[which], 
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

2.3 radio Dialog (Figure 4)

int yourChoice;
private void showSingleChoiceDialog(){
    final String[] items = { "I'm 1","I'm 2","I'm 3","I'm 4" };
    yourChoice = -1;
    AlertDialog.Builder singleChoiceDialog = 
        new AlertDialog.Builder(MainActivity.this);
    singleChoiceDialog.setTitle("I'm a single choice Dialog");
    // The second parameter is the default option, which is set to 0 here
    singleChoiceDialog.setSingleChoiceItems(items, 0, 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            yourChoice = which;
        }
    });
    singleChoiceDialog.setPositiveButton("Determine", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (yourChoice != -1) {
                Toast.makeText(MainActivity.this, 
                "You chose" + items[yourChoice], 
                Toast.LENGTH_SHORT).show();
            }
        }
    });
    singleChoiceDialog.show();
}

2.4 multi select Dialog (Figure 5)

ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
    final String[] items = { "I'm 1","I'm 2","I'm 3","I'm 4" };
    // Set the option selected by default, all false, none selected by default
    final boolean initChoiceSets[]={false,false,false,false};
    yourChoices.clear();
    AlertDialog.Builder multiChoiceDialog = 
        new AlertDialog.Builder(MainActivity.this);
    multiChoiceDialog.setTitle("I'm a multiple choice Dialog");
    multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
        new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which,
            boolean isChecked) {
            if (isChecked) {
                yourChoices.add(which);
            } else {
                yourChoices.remove(which);
            }
        }
    });
    multiChoiceDialog.setPositiveButton("Determine", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            int size = yourChoices.size();
            String str = "";
            for (int i = 0; i < size; i++) {
                str += items[yourChoices.get(i)] + " ";
            }
            Toast.makeText(MainActivity.this, 
                "You chose" + str, 
                Toast.LENGTH_SHORT).show();
        }
    });
    multiChoiceDialog.show();
}

2.5 wait for Dialog (Figure 6)

private void showWaitingDialog() {
    /* Wait for Dialog to have the ability to block the interaction of other controls
     * @setCancelable To make the screen non clickable, set to non cancelable (false)
     * After the download and other events are completed, call the function actively to close the Dialog
     */
    ProgressDialog waitingDialog= 
        new ProgressDialog(MainActivity.this);
    waitingDialog.setTitle("I am a waiting Dialog");
    waitingDialog.setMessage("Waiting...");
    waitingDialog.setIndeterminate(true);
    waitingDialog.setCancelable(false);
    waitingDialog.show();
}

2.6 progress bar Dialog (Figure 7)

private void showProgressDialog() {
    /* @setProgress Set initial progress
     * @setProgressStyle Style (horizontal progress bar)
     * @setMax Set progress maximum
     */
    final int MAX_PROGRESS = 100;
    final ProgressDialog progressDialog = 
        new ProgressDialog(MainActivity.this);
    progressDialog.setProgress(0);
    progressDialog.setTitle("I am a progress bar Dialog");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMax(MAX_PROGRESS);
    progressDialog.show();
    /* Simulate the process of progress increase
     * Open a new thread, each 100ms, the progress increases by 1
     */
    new Thread(new Runnable() {
        @Override
        public void run() {
            int progress= 0;
            while (progress < MAX_PROGRESS){
                try {
                    Thread.sleep(100);
                    progress++;
                    progressDialog.setProgress(progress);
                } catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            // When the progress reaches the maximum value, the window disappears
            progressDialog.cancel();
        }
    }).start();
}

2.7 edit Dialog (Figure 8)

private void showInputDialog() {
    /*@setView Load an EditView
     */
    final EditText editText = new EditText(MainActivity.this);
    AlertDialog.Builder inputDialog = 
        new AlertDialog.Builder(MainActivity.this);
    inputDialog.setTitle("I'm an input Dialog").setView(editText);
    inputDialog.setPositiveButton("Determine", 
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this,
            editText.getText().toString(), 
            Toast.LENGTH_SHORT).show();
        }
    }).show();
}

2.8 custom Dialog (Figure 9)

<!-- res/layout/dialog_customize.xml-->
<!-- custom View -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        />
</LinearLayout>


private void showCustomizeDialog() {
    /* @setView Load custom view = = > r.layout.dialog "Customize
     * Because dialog "customize. XML only places one EditView, it is the same as figure 8
     * dialog_customize.xml More complex views can be customized
     */
    AlertDialog.Builder customizeDialog = 
        new AlertDialog.Builder(MainActivity.this);
    final View dialogView = LayoutInflater.from(MainActivity.this)
        .inflate(R.layout.dialog_customize,null);
    customizeDialog.setTitle("I'm a custom Dialog");
    customizeDialog.setView(dialogView);
    customizeDialog.setPositiveButton("Determine",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // Get input from EditView
            EditText edit_text = 
                (EditText) dialogView.findViewById(R.id.edit_text);
            Toast.makeText(MainActivity.this,
                edit_text.getText().toString(),
                Toast.LENGTH_SHORT).show();
        }
    });
    customizeDialog.show();
}

3. Copy callback function

/* To copy the create and show functions of Builder, you can implement the necessary settings before the Dialog is displayed
 * For example, initialization list, default options, etc
 * @create Called on first creation
 * @show Called every time displayed
 */
private void showListDialog() {
    final String[] items = { "I'm 1","I'm 2","I'm 3","I'm 4" };
    AlertDialog.Builder listDialog = 
        new AlertDialog.Builder(MainActivity.this){

        @Override
        public AlertDialog create() {
            items[0] = "I am No.1";
            return super.create();
        }

        @Override
        public AlertDialog show() {
            items[1] = "I am No.2";
            return super.show();
        }
    };
    listDialog.setTitle("I'm a list Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    /* @setOnDismissListener Dialog Called on destroy
     * @setOnCancelListener Dialog Called on close
     */
    listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        public void onDismiss(DialogInterface dialog) {
            Toast.makeText(getApplicationContext(),
                "Dialog Destroyed", 
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

Posted by netbros on Fri, 01 May 2020 15:18:07 -0700