首先我們定義一個界面

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingTop="10dp"> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/title" android:scaleType="fitXY"/> <EditText android:id="@+id/nameET" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="用戶名"/> <EditText android:id="@+id/pwdET" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密碼"/> </LinearLayout>
放在這
然后我們加載布局文件就可以了

//新建一個view View customView = View.inflate(this,R.layout.custom_dialog,null); //獲取view的內容 final EditText nameET = customView.findViewById(R.id.nameET); final EditText pwdET = customView.findViewById(R.id.pwdET); //展示對話框 new AlertDialog.Builder(this) .setView(customView) .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = nameET.getText().toString(); String pwd = pwdET.getText().toString(); String msg = name+" "+pwd; System.out.println(msg); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("取消",null) .show();