如何自定义Android AlertDialog中的列表项

时间:2010-08-29 10:14:57

标签: android list customization alertdialog

我想使用AlertDialog为列表中的每个项目显示多行具有不同文本样式的行,但不能用任何示例。

有谁知道如何自定义AlertDialog的项目?或者我真的必须为此创建一个带有ListView的Activity吗?

2 个答案:

答案 0 :(得分:13)

使用setAdapter()上的AlertDialog.Builder为您的列表提供自己的自定义ListAdapter

答案 1 :(得分:6)

有关上述想法的实施,请参阅THIS LINK

编辑:顺便说一句,我做了一些更改,实际上显示了不同的图标:

list_item.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/icon"
        android:contentDescription="@string/icon_descr"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_gravity="left" />

    <TextView
        android:id="@+id/title"
        android:text=""
        android:paddingLeft="10dip"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

进入你的活动:

// dialog list entries
final String[] items = {
    getString(R.string.entry_0),
    getString(R.string.entry_1),
    getString(R.string.entry_2)
};

// dialog list icons: some examples here
final int[] icons = {
    android.R.drawable.ic_menu_edit,
    android.R.drawable.ic_menu_send,
    android.R.drawable.ic_menu_delete
};

ListAdapter adapter = new ArrayAdapter<String>(
    getApplicationContext(), R.layout.list_item, items) {

    ViewHolder holder;

    class ViewHolder {
        ImageView icon;
        TextView title;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
    final LayoutInflater inflater = (LayoutInflater) getApplicationContext()
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {
        convertView = inflater.inflate(
        R.layout.list_item, null);

        holder = new ViewHolder();
        holder.icon = (ImageView) convertView
        .findViewById(R.id.icon);
        holder.title = (TextView) convertView
        .findViewById(R.id.title);
        convertView.setTag(holder);
    } else {
        // view already defined, retrieve view holder
        holder = (ViewHolder) convertView.getTag();
    }     

    holder.title.setText(items[position]);

    holder.icon.setImageResource(icons[position]);
    return convertView;
    }
};

// ----------

AlertDialog.Builder builder = new AlertDialog.Builder(myActivity.this);

builder.setTitle("title");

builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        // ---
    }

});

builder.create();
if (! ((Activity) myActivity.this).isFinishing()) {
    builder.show();
}