如何在警报对话框中的每个项目之前添加图标? [英] How to add an icon before each item in alert dialog?
本文介绍了如何在警报对话框中的每个项目之前添加图标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用AlertDialog(请参见下面的代码),并希望在每个文本之前放置一个图像.
I am using an AlertDialog (see the below code) and would like to put an image before each text.
例如,电子邮件图标,然后输入文字"Email",Facebook图标,然后输入文字"Facebook",等等.
For example, email icon then text "Email", Facebook icon then text "Facebook", etc.
使用以下代码,如何在每个文本值之前添加图标?
Using the following code, how to add an icon before each text value?
final CharSequence[] items = { "Email", "Facebook", "Twitter", "LinkedIn" };
AlertDialog.Builder builder = new AlertDialog.Builder(More.this);
builder.setTitle("Share Appliction");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
} else if (item == 1) {
} else if (item == 2) {
} else if(item == 3) {
}
}
});
AlertDialog alert = builder.create();
alert.show();
推荐答案
您需要自定义ListAdapter
来添加图像.一种方法是将ArrayAdapter
子类化(默认情况下由AlertDialog
使用).这是一个示例:
You need custom ListAdapter
to add your image. One way is to subclass the ArrayAdapter
(used by default by the AlertDialog
). Here is an example:
final Item[] items = {
new Item("Email", android.R.drawable.ic_menu_add),
new Item("Facebook", android.R.drawable.ic_menu_delete),
new Item("...", 0),//no icon for this one
};
ListAdapter adapter = new ArrayAdapter<Item>(
this,
android.R.layout.select_dialog_item,
android.R.id.text1,
items){
public View getView(int position, View convertView, ViewGroup parent) {
//Use super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView)v.findViewById(android.R.id.text1);
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
//Add margin between image and text (support various screen densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
new AlertDialog.Builder(this)
.setTitle("Share Appliction")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//...
}
}).show();
这是Item类
public static class Item{
public final String text;
public final int icon;
public Item(String text, Integer icon) {
this.text = text;
this.icon = icon;
}
@Override
public String toString() {
return text;
}
}
这篇关于如何在警报对话框中的每个项目之前添加图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文