Android learning: dialog box and message box

Android learning: dialog box and message box

Learning points: 1. Understand the basic functions of various dialog boxes in the Android system

2. Master the method of using AlertDialog to create dialog boxes

3. Master the method of using Toast to create a message prompt box

1. Use AlertDialog to create a dialog box

The dialog box is the interface displayed when the Activity is running, and it is one of the main ways for the application to interact with the user. accomplish.

When the dialog box prompts, the current Activity will lose focus. At this time, the user cannot interact with the Activity, and when the dialog box gets the focus, the user can operate the dialog box.

There are many types of dialog boxes in the Android system, mainly including ordinary dialog boxes, dialog boxes containing buttons, radio button dialog boxes, check box dialog boxes, list dialog boxes, data input dialog boxes, and progress bar dialog box date dialog boxes. box and the time dialog. In addition, users can also customize the dialog box.

Introduction to AlertDialog Construction Method

The AlertDialog construction method is of the Protected type, so you cannot create an AlertDialog directly through new, but use the create() method in AlertDialog.Builder.

1. setTitle: Set the title for the dialog box

2. setIcon: Set the icon for the dialog box

3. setMessage: set the content for the dialog box

4. setView: Set a custom style for the dialog box

5. setItems: set a list to be displayed in the dialog box, generally used when several commands are to be displayed

6. setMultiChoiceItems: Used to set the dialog box to display a series of check boxes

7. setNeutralButton: used to set the normal button

8. setPositiveButton: Add a Yes button to the dialog box

9. setNegativeButton: Add a No button to the dialog box

10. create: Create dialog box

11. show: Display the dialog box.

The specific exercise code is as follows:

//XML代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="5种类型\n常用对话框"
        android:textAlignment="center"
        android:textColor="@android:color/black"/>
    <Space
        android:layout_width="match_parent"
        android:layout_height="20dp" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确定/取消对话框"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单选对话框" />
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="多选对话框"/>
    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="列表对话框"/>
    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="可输入对话框"/>
    <Space
        android:layout_width="match_parent"
        android:layout_height="20dp" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="获得的对话框结果"
        android:textColor="@android:color/black"/>
</LinearLayout>
            
//MainActivity页面代码
package zut.edu.e8;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    //选项数组(喜欢的出行方式)
    final String[] travelType = {"高铁", "飞机", "汽车"};
    //获取选项
    private String selectedItem = "";
    //获取另一个选项
    private String selectedItem2 = "";
    //选项初始化
    private boolean[] init = new boolean[]{false, true, false};
    //默认选项
    private boolean[] mtemp = new boolean[3];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //选项初始化暂缓
        for(int i = 0;i<init.length;i++){
            mtemp[i] = init[i];
        }
        //实例化一个TextView,用于显示选项结果
        final TextView textView1 = (TextView) findViewById(R.id.textView1);
        /* 1/5 : 确定/取消对话框 */
        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                textView1.setText("");
                //实例化一个AlertDialog对象
                new AlertDialog.Builder(MainActivity.this)
                        //为对话框设置图标
                        .setIcon(R.drawable.ic_launcher)
                        //设置对话框标题
                        .setTitle("提示")
                        //设置对话框内容
                        .setMessage("是否退出程序?")
                        //"确定"按钮单击事件,退出当前程序
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();//退出当前程序
                                    }
                                })
                        //取消按钮单击,关闭对话框
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        textView1.setText("你单击了取消按钮。");
                                    }
                                })
                        //创建并显示对话框
                        .create().show();
            }
        });
        /* 2/5 单选对话框 */
        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView1.setText("");
                selectedItem = travelType[1]; //1.为单选对话框中的checkedItem(默认选项)
                new AlertDialog.Builder(MainActivity.this)
                        .setIcon(R.drawable.ic_launcher)
                        .setTitle("请选择你最喜欢出行方式")
                        //设置对话框类型
                        .setSingleChoiceItems(travelType, 1,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //MainActivity.this.selectedItem = which;
                                        selectedItem = travelType[which];
                                        textView1.setText("你选择了:"+
                                        selectedItem);
                                    }
                                })
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        textView1.setText("你最终的选择是:"+
                                        selectedItem);
                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        textView1.setText("你取消了选择。");
                                    }
                                })
                        .create().show();
            }
        });
                /* 3/5 复选对话框  */
                Button button3 = (Button)findViewById(R.id.button3);
                button3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView1.setText("");
                        new AlertDialog.Builder(MainActivity.this)
                                .setIcon(R.drawable.ic_launcher)
                                .setTitle("请选择你喜欢的出行方式:")
                                .setMultiChoiceItems(travelType, init,
                                        new DialogInterface.OnMultiChoiceClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                                selectedItem = travelType[which];
                                                if(init[which]){
                                                    textView1.setText("你选择了:" +
                                                    selectedItem);
                                                }
                                                else {
                                                    textView1.setText("你取消了选择的:"+
                                                    selectedItem);
                                                }
                                            }
                                        })
                                .setPositiveButton("确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                String temp = "";
                                                //遍历获取所选项
                                                for (int i= 0;i<init.length;i++){
                                                    if (init[i]){
                                                        temp += "/n" + travelType[i];
                                                    }
                                                }
                                                textView1.setText("你的最终选择是:"+temp);
                                                //还原默认选项
                                                for (int i = 0;i<init.length;i++){
                                                    init[i] = mtemp[1];
                                                }
                                            }
                                        })
                                .setNegativeButton("取消",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                textView1.setText("你取消了选择。");
                                            }
                                        })
                                .create().show();
                    }
                });
                /* 4/5 列表对话框   */
                Button button4 = (Button)findViewById(R.id.button4);
                button4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView1.setText("");
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("请选择出你喜欢的出行方式:")
                                .setIcon(R.drawable.ic_launcher)
                                .setItems(travelType, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // MainActivity.this.selectedItem = which
                                        selectedItem2 = travelType[which];
                                        textView1.setText("你选择了:"+selectedItem2);
                                    }
                                })
                                //注:通常无须再为“确定”和“取消”按钮编写相应程序
                                .create().show();
                    }
                });
                /*  5/5 可输入对话框 */
                Button button5 = (Button)findViewById(R.id.button5);
                button5.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //实例化一个EditText,用于接收用户输入
                        final EditText travelInput = new EditText(MainActivity.this);
                        new AlertDialog.Builder(MainActivity.this)
                                .setIcon(R.drawable.ic_launcher)
                                .setTitle("请输入你喜欢的出行方式:")
                                .setView(travelInput)
                                .setPositiveButton("确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                textView1.setText("你输入的是:"+travelInput.getText().toString());
                                            }
                                        })
                                .setNegativeButton("取消",
                                        new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        textView1.setText("你取消了选择。");
                                    }
                                })
                                .create().show();
                    }
                });
    }
}

[Explanation] In the Android2.X version, the "OK/OK" button is located on the left side of the dialog box, and the "Cancel/Cancel" button is located on the right side of the dialog box, but in 4.0 and later versions, the positions are reversed.

2. Use Toast to display the message prompt box

In the Android system, if only a small prompt pops up, and the corresponding information is displayed briefly and briefly to the user (such as a volume control prompt or a successful message save prompt, etc.), without requiring the user to perform other operations, you can use Toast to implement (display a hint or instructions)

Toast is a concise information view provided by the Android system, which floats above the application. Unlike Dialog, Toast has no focus, so even if the user is typing, it does not affect the display of the view. In addition, the time displayed by Toast is limited, and it will disappear automatically after a certain period of time.

1. Introduction to Toast

Toast is a class that mainly manages message prompts.

makeText (Context context, String text, int Toast.LENGTH_LONG/Toast.LENGTH_SHORT) is a method of Toast, which is used to display corresponding information. The definitions of its three parameters are as follows:

The first parameter: the context parameter, if context is equal to this, it means to display on the current page

The second parameter: the content to be displayed

The third parameter: two optional display time parameters, Toast.LENGTH_LONG time is slightly longer (about 3.5s), Toast.LENGTH_SHORT time is slightly shorter (about 2s)

The Toast message reminder box is displayed through the show() method, so the basic code of Toast is

Toast.makeText(context,text,Toast.LENGTH_LONG).show()

or

Toast.makeText(context,text,Toast.LENGTH_SHORT).show()

The specific exercise code is as follows:

//XML代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn01"
        android:text="确认取消按钮"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvMsg"
        android:text="提示框"/>
</LinearLayout>
//MainActivity页面代码
package zut.edu.e9;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    final String[] travelType={"高铁","飞机","汽车"};
    String selectItem;//选中项
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn01=(Button)findViewById(R.id.btn01);
        final TextView tvMsg=(TextView) findViewById(R.id.tvMsg);
        //代码应该在按钮单击事件里面
        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //对话框放在按钮时间里面
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择出行方式")
                        .setSingleChoiceItems(travelType, 1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {
                                selectItem=travelType[which];//将当前选择索引复制给数组,取值
                                tvMsg.setText("你选择了"+selectItem);
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                tvMsg.setText("你的选择是:"+selectItem);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                // tvMsg.setText("你取消了"+selectItem);
                                //1.当前类 2.内容
                                Toast.makeText(MainActivity.this,"选择取消",Toast.LENGTH_LONG).show();
                            }
                        })
                        .create().show();
            }
        });
    }
}

Guess you like

Origin blog.csdn.net/weixin_52021660/article/details/123882058