XML布局來寫ALTERDailog
时间: 2023-06-23 15:09:58 浏览: 57
在Android中,可以使用XML布局来定义AlertDialog的布局和样式。下面是一个简单的示例:
首先,在res/layout文件夹中创建一个XML布局文件,例如dialog_layout.xml:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dialog Title"
android:textColor="@color/colorAccent"
android:textSize="18sp"
android:textStyle="bold" />
<EditText
android:id="@+id/dialog_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter input here" />
</LinearLayout>
```
接下来,在Java代码中使用AlertDialog.Builder创建AlertDialog,并将布局设置为它的视图:
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Dialog Title");
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View dialogView = getLayoutInflater().inflate(R.layout.dialog_layout, null);
builder.setView(dialogView);
// Add action buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
EditText input = dialogView.findViewById(R.id.dialog_input);
String userInput = input.getText().toString();
// Do something with user input
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
```
在此示例中,我们使用LinearLayout作为根视图,其中包含一个TextView和一个EditText。我们使用AlertDialog.Builder创建AlertDialog,并在其中设置标题和视图。我们还添加了PositiveButton和NegativeButton,以便用户可以执行某些操作或取消对话框。
在点击PositiveButton时,我们获取EditText的值并执行某些操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)