要使用AlertDialog.Builder顯示自定義視圖,請按照以下步驟操作:
dependencies {
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
}
custom_dialog.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="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定義視圖"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="點擊我" />
</LinearLayout>
showCustomDialog()
,并使用AlertDialog.Builder構(gòu)建一個包含自定義視圖的對話框:private void showCustomDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View customView = inflater.inflate(R.layout.custom_dialog, null);
builder.setView(customView);
// 設(shè)置其他對話框?qū)傩?,例如標題、按鈕等
builder.setTitle("自定義視圖");
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理點擊確定按鈕的事件
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 處理點擊取消按鈕的事件
dialog.dismiss();
}
});
// 顯示對話框
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
showCustomDialog()
方法。例如,你可以在按鈕的點擊事件中調(diào)用這個方法:button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog();
}
});
現(xiàn)在,當(dāng)你點擊按鈕時,應(yīng)該會看到一個包含自定義視圖的AlertDialog。