fragment 中dialog怎么使用
时间: 2024-01-18 22:03:18 浏览: 25
在 Android 中,可以通过使用 DialogFragment 类来创建和管理对话框。下面是一个简单的示例,演示如何创建和使用 DialogFragment:
首先,在您的项目中创建一个新的 DialogFragment 类,例如:
```java
public class MyDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Create a new AlertDialog.Builder instance
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle("My Dialog");
// Set the dialog message
builder.setMessage("Hello, World!");
// Set the positive button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
// Set the negative button
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Return the created dialog
return builder.create();
}
}
```
然后,在您的 Activity 或 Fragment 中,可以通过调用以下代码来显示 DialogFragment:
```java
MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getFragmentManager(), "MyDialogFragment");
```
这将在屏幕上显示一个对话框,其中包含标题为 "My Dialog",消息为 "Hello, World!",和两个按钮 "OK" 和 "Cancel"。
当用户点击其中一个按钮时,相应的 onClick() 回调将被触发。在上面的示例中,如果用户点击 "OK" 按钮,则会触发其相应的回调并执行其中的代码。