Android APP开发08(AlertDialog)
作者:互联网
AlertDialog
实现方式
AlertDialog.Builder builder =new AlertDialog.Builder(context);
构建Dialog的各种参数
方法
方法名 | 解析 |
---|---|
Builder.setIcon(int iconId) | 添加ICON |
Builder.setTitle(CharSequence title) | 添加标题 |
Builder.setMessage(CharSequence msg) | 添加消息 |
Builder.setView(View view) | 设置自定义布局 |
Builder.create() | 创建Dialog |
Builder.show() | 显示对话框 |
setPositiveButton | 确定按钮 |
setNegativeButton | 取消按钮 |
setNeutralButton | 中间按钮 |
实例
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" xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="显示对话框"
android:onClick="showalert"
/>
</LinearLayout>
java
package com.example.myalertdialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showalert(View view){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("我是对话框")
.setMessage("CSDN博客:碰磕")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.e("leo","点击了确定");
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.e("leo","点击了取消");
}
})
.setNeutralButton("中间", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.e("leo","点击了中间");
}
})
.create().show();
}
}
效果
通过点击不同的选择,会做出相对于的操作
还可以自定义布局
只需要创建一个xml
dialog_view.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:background="#ffff00"
android:orientation="horizontal">
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="碰磕"
/>
</LinearLayout>
在java中加入
View dialogview=getLayoutInflater().inflate(R.layout.dialog_view,null);
builder.setView(dialogview)
最终效果:
dialog弹窗测试就完成了…
标签:Builder,DialogInterface,AlertDialog,void,new,import,Android,APP 来源: https://blog.csdn.net/m_xiaozhilei/article/details/122751636