一、前言:点击按钮出现提示

二、上代码

新建一个活动AlertDialogActivity

public class AlertDialogActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_dialog);
        findViewById(R.id.btn_dialog).setOnClickListener(this);
        tv_result = findViewById(R.id.tv_result);
    }

    @Override
    public void onClick(View view) {
        //创建提醒对话框的建构器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //设置对话框的标题文本
        builder.setTitle("尊敬的用户");
        //设置对话框的内容文本
        builder.setMessage("你真的要卸载我嘛?");
        //设置对话框肯定文本及按钮点击事件
        builder.setPositiveButton("残忍卸载", (dialogInterface, i) -> {
            tv_result.setText("虽然依依不舍,但是只能离开了");
        });
        //设置对话框否定文本按钮点击事件
        builder.setNegativeButton("残忍卸载", (dialogInterface, i) -> {
            tv_result.setText("让我再陪你三百六十五个日夜吧");
        });
        //根据建构器构建提醒对话框对象
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
}
与之对应的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".dialog.AlertDialogActivity">
    <Button
        android:id="@+id/btn_dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="弹出提醒对话框"/>
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


</LinearLayout>

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐