对话框AlertDialog基本使用及自定义Alertdialog、Fragment动静态创建及来回传参
对话框AlertDialog
1.在MainActivity.java中
1)AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
new 一个对象
使用AlertDialog.Builder——起名:ab
new AlertDialog.Builder(MainActivity.this);——context
2)设置属性:setTitle(“设置Title”);
setMessage(“设置消息”);
3)ab.setPositiveButton(“确定”, new DialogInterface.OnClickListener() {
setPositiveButton——确定;OnClickListener()-设置点击事件
setNegativeButton——取消
4).show()
package com.example.myapplication;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
ab.setTitle("设置Title");
ab.setMessage("设置消息");
ab.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"点的是确定",Toast.LENGTH_LONG).show();
}
});
ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"点的是取消",Toast.LENGTH_LONG).show();
}
});
ab.show();
}
});
}
}
2.在activity_main.xml中
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点我弹出消息对话框"></Button>
效果图:
自定义Alertdialog
1.创建布局文件layout(显示内容)起名:mydialog
在mydialog.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:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="请输入密码"
android:textSize="30sp"></TextView