Android中對話框的使用方法有以下幾種:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("對話框標題");
builder.setMessage("對話框內容");
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) {
// 點擊取消按鈕后的操作
}
});
AlertDialog dialog = builder.create();
dialog.show();
首先創建一個繼承自DialogFragment的類,重寫onCreateDialog方法:
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("對話框標題");
builder.setMessage("對話框內容");
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) {
// 點擊取消按鈕后的操作
}
});
return builder.create();
}
}
然后在需要顯示對話框的地方調用:
MyDialogFragment dialogFragment = new MyDialogFragment();
dialogFragment.show(getSupportFragmentManager(), "dialog");
首先創建一個自定義布局文件,例如dialog_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/dialog_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="對話框標題"
android:textSize="18sp"
android:textColor="#000000"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/dialog_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="確認"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
然后在需要顯示對話框的地方調用:
LayoutInflater inflater = LayoutInflater.from(this);
View dialogView = inflater.inflate(R.layout.dialog_layout, null);
TextView titleTextView = dialogView.findViewById(R.id.dialog_title);
Button button = dialogView.findViewById(R.id.dialog_button);
titleTextView.setText("對話框標題");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 點擊按鈕后的操作
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.show();
以上是幾種常見的Android對話框的使用方法,根據不同需求選擇合適的方法即可。