android自定义对话框
In this tutorial, we’ll be discussing and implementing Custom Alert Dialogs in our Android Application.
We’d discussed Android Alert Dialogs already here.
在本教程中,我们将在Android应用程序中讨论和实现“自定义警报对话框”。
我们已经在这里讨论了Android Alert对话框。
警报对话框 (Alert Dialogs)
Alert Dialogs by default are used to create dialogs with text messages and button actions.
Following are the setter methods that we’d already discussed in the previous tutorial.
默认情况下,“警报对话框”用于创建带有文本消息和按钮操作的对话框。
以下是我们在上一教程中已经讨论过的setter方法。
- setTitle setTitle
- setMessage setMessage
- setPositiveButton setPositiveButton
- setNegativeButton setNegativeButton
- setNeutralButton setNeutralButton
- setPositiveButtonIcon/setNegativeButtonIcon/setNeutralButtonIcon setPositiveButtonIcon / setNegativeButtonIcon / setNeutralButtonIcon
- setCancelable setCancelable
- setIcon setIcon
- setOnDismissListener setOnDismissListener
- setItems – shows an array of items in the form of a list inside the alert dialog setItems –在警报对话框内以列表形式显示项目数组
- setMultiChoiceItems – Sets a list of items to choose from inside the alert dialog setMultiChoiceItems –设置要在警报对话框中选择的项目列表
- setView – Used to set a custom layout view inside the alert dialog. setView –用于在警报对话框中设置自定义布局视图。
- show() 表演()
- setShowListener() – This is triggered when the alert dialog is displayed on the screen. We can do any dynamic changes in here setShowListener()–在屏幕上显示警报对话框时触发。 我们可以在这里进行任何动态更改
In the following section we’ll create different types of custom alert dialog:
在以下部分中,我们将创建不同类型的自定义警报对话框:
- With List of Items 带项目清单
- With EditText 使用EditText
- With ImageView 使用ImageView
- With SeekBar 与SeekBar
- With RatingBar 有RatingBar
项目结构 (Project Structure)
码 (Code)
The code for the activity_main.xml layout file is given below:
下面给出了activity_main.xml布局文件的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btnSimpleAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="simpleAlert"
android:text="SIMPLE ALERT DIALOG"/>
<Button
android:id="@+id/btnAlertWithItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withItems"
android:text="WITH ITEMS"/>
<Button
android:id="@+id/btnAlertWithMultiChoiceItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withMultiChoiceItems"
android:text="WITH MULTI CHOICE ITEMS"/>
<Button
android:id="@+id/btnAlertWithEditText"
android:layout_width="wrap_content"
android:onClick="withEditText"
android:layout_height="wrap_content"
android:text="WITH EDIT TEXT"/>
<Button
android:id="@+id/btnAlertWithImageView"
android:layout_width="wrap_content"
android:onClick="withImageView"
android:layout_height="wrap_content"
android:text="WITH IMAGE VIEW"/>
<Button
android:id="@+id/btnAlertWithSeekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="withSeekBar"
android:text="WITH SEEK BAR"/>
<Button
android:id="@+id/btnAlertWithRatingBar"
android:layout_width="wrap_content"
android:onClick="withRatingBar"
android:layout_height="wrap_content"
android:text="WITH RATING BAR"/>
</LinearLayout>
Each of the Buttons would create an AlertDialog. We’ve set the onClick method for each of them which would be defined in the MainActivity.java class.
每个按钮将创建一个AlertDialog。 我们为每个方法都设置了onClick方法,该方法将在MainActivity.java类中定义。
简单警报对话框 (Simple Alert Dialog)
Add the following method(s) to your MainActivity.java:
将以下方法添加到您的MainActivity.java中:
public void simpleAlert(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Simple Alert");
builder.setMessage("We have a message");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"OK was clicked",
Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
android.R.string.no, Toast.LENGTH_SHORT).show();
}
});
builder.setCancelable(false);
builder.show();
}
This is the simplest form of AlertDialog. Let’s get onto the more interesting ones.
这是AlertDialog的最简单形式。 让我们来看一些更有趣的。
AlertDialog.Builder
is used to build the AlertDialog.
AlertDialog.Builder
用于构建AlertDialog。
To display the AlertDialog we can alternatively use the following code as well:
要显示AlertDialog,我们也可以使用以下代码:
AlertDialog alertDialog = builder.create();
alertDialog.show();
AlertDialog显示项目列表 (AlertDialog Showing List Of Items)
public void withItems(View view) {
final String[] items = {"Apple", "Banana", "Orange", "Grapes"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("List of Items")
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), items[which] + " is clicked", Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("OK", null);
builder.setNegativeButton("CANCEL", null);
builder.setNeutralButton("NEUTRAL", null);
builder.setPositiveButtonIcon(getResources().getDrawable(android.R.drawable.ic_menu_call, getTheme()));
builder.setIcon(getResources().getDrawable(R.drawable.jd, getTheme()));
AlertDialog alertDialog = builder.create();
alertDialog.show();
Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
button.setBackgroundColor(Color.BLACK);
button.setPadding(0, 0, 20, 0);
button.setTextColor(Color.WHITE);
}
In the setItems
method we pass the array of strings we want to display.
which
argument contains the index of the list item that is clicked.
在setItems
方法中,我们传递要显示的字符串数组。
which
参数包含被单击列表项的索引。
We can customize the Button texts and style by retrieving the Button instances over the alertDialog instance and setting the text color etc.
我们可以通过在alertDialog实例上检索Button实例并设置文本颜色等来自定义Button文本和样式。
colorAccent
value defined in the styles.xml
colorAccent
值设置的
具有多个选择列表的AlertDialog (AlertDialog With Multiple Selection List)
public void withMultiChoiceItems(View view) {
final String[] items = {"Apple", "Banana", "Orange", "Grapes"};
final ArrayList<Integer> selectedList = new ArrayList<>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This is list choice dialog box");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedList.add(which);
} else if (selectedList.contains(which)) {
selectedList.remove(which);
}
}
});
builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ArrayList<String> selectedStrings = new ArrayList<>();
for (int j = 0; j < selectedList.size(); j++) {
selectedStrings.add(items[selectedList.get(j)]);
}
Toast.makeText(getApplicationContext(), "Items selected are: " + Arrays.toString(selectedStrings.toArray()), Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
This is a better version of the simple list of items that we saw earlier.
Each of the items in the list has a CheckBoxbeside it. The isChecked
boolean value returns the checkBox current state.
这是我们之前看到的简单项目清单的更好版本。
列表中的每个项目旁边都有一个CheckBox 。 isChecked
布尔值返回checkBox当前状态。
Once the Button is clicked, we show the list of items that were selected by converting the ArrayList populated of the selectedItems into an Array.
单击“按钮”后,我们将通过将由selectedItems填充的ArrayList转换为Array来显示所选项目的列表。
具有EditText的AlertDialog (AlertDialog With EditText)
Using the setView property we can set a custom view from the layout or do that programmatically as well.
In the below function we've done it programmatically.
使用setView属性,我们可以从布局中设置自定义视图,也可以通过编程方式进行。
在下面的函数中,我们以编程方式完成了此操作。
public void withEditText(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("With Edit Text");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "Text entered is " + input.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
使用ImageView的警报对话框 (Alert Dialog With ImageView)
Here we'll inflate a custom layout inside our setView
method.
Following is the layout that'll be shown inside the AlertDialog:
在这里,我们将在setView
方法中setView
自定义布局。
以下是将在AlertDialog中显示的布局:
alert_dialog_with_imageview.xml
alert_dialog_with_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="350dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:src="@drawable/sample"/>
</LinearLayout>
Add the following function inside your MainActivity.java class:
在MainActivity.java类中添加以下函数:
public void withImageView(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_imageview, null);
builder.setPositiveButton("OK", null);
builder.setView(dialogLayout);
builder.show();
}
带有搜索栏的警报对话框 (Alert Dialog With Seekbar)
public void withSeekBar(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("With SeekBar");
final SeekBar seekBar = new SeekBar(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
seekBar.setLayoutParams(lp);
builder.setView(seekBar);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "Progress is " + seekBar.getProgress(), Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
On clicking the Button we show the progress value of the SeekBar.
单击按钮后,我们将显示SeekBar的进度值。
带等级栏的警报对话框 (Alert Dialog With Rating Bar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RatingBar
android:id="@+id/ratingBar"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="0.5" />
</LinearLayout>
public void withRatingBar(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
builder.setTitle("With RatingBar");
View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_ratingbar, null);
final RatingBar ratingBar = dialogLayout.findViewById(R.id.ratingBar);
builder.setView(dialogLayout);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(), "Rating is " + ratingBar.getRating(), Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
Once you've added all the above methods inside the MainActivity.java class let's build and run our application. Following is the output of the above application in action.
在MainActivity.java类中添加了上述所有方法之后,就可以构建并运行我们的应用程序。 以下是上述应用程序的输出。
This brings an end to this tutorial. You can download the project from the link below:
本教程到此结束。 您可以从下面的链接下载项目:
翻译自: https://www.journaldev.com/22153/android-custom-alert-dialog
android自定义对话框