且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Android中创建自定义共享对话框

更新时间:2023-01-23 21:15:50

我遇到了这个问题.我在答案中找到了解决方案,希望对您也有帮助.

i faced this problem. i found solution in this answer i hope it helps you too..

如果以后不存在,我会在下面写这篇文章的代码:

I write the code of this post below in case of not exist in the future:

您必须使用自定义ListAdapter来添加图像.即将继承的是ArrayAdapter的子类(默认情况下由AlertDialog使用).这是一个示例:

You must use a custom ListAdapter to add your image. On 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;
    }
}