原生的简单调用
代码如下:
AlertDialog dialog;
dialog=new AlertDialog.Builder(context)
.setTitle("This is a title!")
.setMessage("This is a message!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MyUtils.showToast(context,"Click Ok!Then do something.");
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
自定义AlertDialog
java代码:
private void initCustomDialog(int resId) {//传入自定义xml布局资源id
View customView=LayoutInflater.from(context).inflate(resId,null);
dialog=new AlertDialog.Builder(context)
.setView(customView)
.create();
TextView tvCancel=customView.findViewById(R.id.tvCancel);
TextView tvSure=customView.findViewById(R.id.tvSure);
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
tvSure.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyUtils.showToast(context,"do something!");
dialog.dismiss();
}
});
dialog.show();
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:text="CustomTitle"
android:textSize="25dp"
android:gravity="center"
android:background="#ff00ff"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:gravity="center"
android:textSize="20dp"
android:background="#55ff55"
android:text="This is a Custom Message!"
android:layout_width="match_parent"
android:layout_height="100dp" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:background="#88ffff"
android:layout_height="50dp">
<TextView
android:id="@+id/tvCancel"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Cancel"
android:textSize="20dp"
android:gravity="center"
android:layout_height="match_parent" />
<View
android:background="#55ff55"
android:layout_width="1dp"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/tvSure"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Ok"
android:textSize="20dp"
android:gravity="center"
android:layout_height="match_parent" />
</LinearLayout>
</LinearLayout>
运行效果图如下:
GitHub地址:https://github.com/BingaChen/project_pool
微信公众号: