Dialog的应用主要是用来弹出提示,例如错误提示,警告提示等等。
下面是参考某github代码的效果:
github源码:
https://github.com/ansen666/AlertDialog
xml布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">
<Button
android:id="@+id/id_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="退出"/>
</androidx.constraintlayout.widget.ConstraintLayout>
代码逻辑:
package com.gentle.progressdialog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.id_exit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
});
}
private void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");//设置标题
builder.setMessage("确认退出吗?");//设置消息内容
builder.setIcon(R.mipmap.ic_launcher);//设置icon图片
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();//取消dialog
MainActivity.this.finish();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();//显示dialog
}
}