如何在android中的ListPreference的项目中设置图标

2024-02-25

我想将图标设置为ListPreferenceAndroid 中的项目。

写什么内容ListPreference或者在哪里写来设置列表项图标?


当您需要多次使用带有文本/图标的列表首选项时,您可以使用此解决方案。

该版本很大程度上基于卢卡扎尼尼的好版本 http://www.lucazanini.eu/en/2014/android/display-icon-preferences/。我对版本做了一些细微的更改,因此它仅取决于自己的首选项属性。通过这种方式,您可以多次使用它们。请参考他的教程。

@Luca - 非常感谢你!

细微的变化只有:

  • IconPickerPreference.java,见下文。
  • 您不需要对 strings.xml 文件的引用。开始时设置的默认值只是“0”。
  • 您可以通过使用整数而不是字符串来改进此版本。

图标选择器首选项:

// @Based on the nice version of LucaZanini. Thank you!
public class IconPickerPreference extends ListPreference {
    private int currentIndex = 0;

    private class CustomListPreferenceAdapter extends ArrayAdapter<IconItem> {
        private Context context;
        private List<IconItem> icons;
        private int resource;

        public CustomListPreferenceAdapter(Context context, int resource, List<IconItem> objects) {
            super(context, resource, objects);
            this.context = context;
            this.resource = resource;
            this.icons = objects;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(resource, parent, false);

                holder = new ViewHolder();
                holder.iconName = (TextView) convertView.findViewById(R.id.iconName);
                holder.iconImage = (ImageView) convertView.findViewById(R.id.iconImage);
                holder.radioButton = (RadioButton) convertView.findViewById(R.id.iconRadio);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.iconName.setText(icons.get(position).name);

            int identifier = context.getResources().getIdentifier( icons.get(position).file, "drawable", context.getPackageName());
            holder.iconImage.setImageResource(identifier);
            holder.radioButton.setChecked(icons.get(position).isChecked);
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    ViewHolder holder = (ViewHolder) v.getTag();
                    for (int i = 0; i < icons.size(); i++) {
                        if (i == position) {
                            icons.get(i).isChecked = true;
                        } else {
                            icons.get(i).isChecked = false;
                        }
                    }
                    getDialog().dismiss();
                }
            });
            return convertView;
        }
    }

    private class IconItem {
        private String  file;
        private boolean isChecked;
        private String  name;

        public IconItem(CharSequence name, CharSequence file, boolean isChecked) {
            this(name.toString(), file.toString(), isChecked);
        }

        public IconItem(String name, String file, boolean isChecked) {
            this.name = name;
            this.file = file;
            this.isChecked = isChecked;
        }

    }

    private class ViewHolder {
        protected ImageView     iconImage;
        protected TextView      iconName;
        protected RadioButton   radioButton;
    }

    private Context context;
    private ImageView icon;

    private CharSequence[] iconFile;
    private CharSequence[] iconName;
    private List<IconItem> icons;
    private SharedPreferences preferences;
    private Resources resources;
    private String selectedIconFile, defaultIconFile;
    private TextView summary;

    public IconPickerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        resources = context.getResources();
        preferences = PreferenceManager.getDefaultSharedPreferences(context);

        TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.attrs_icon, 0, 0);
        try {
            defaultIconFile = a.getString(R.styleable.attrs_icon_iconFile);
        } finally {
            a.recycle();
        }
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);

        CharSequence[] entries = getEntries();
        CharSequence[] values = getEntryValues();
        selectedIconFile = values[ currentIndex].toString();
        icon = (ImageView) view.findViewById(R.id.iconSelected);
        updateIcon();
        summary = (TextView) view.findViewById( R.id.preference_summary);
        summary.setText( entries[ currentIndex]);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        if (icons != null) {
            for (int i = 0; i < iconName.length; i++) {
                IconItem item = icons.get(i);
                if (item.isChecked) {
                    persistString( "" + i);
                    currentIndex = i;
                    selectedIconFile = item.file;
                    updateIcon();
                    summary.setText(item.name);
                    break;
                }
            }
        }
    }

    @Override
    protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
        String number = "0";
        if (restorePersistedValue) {
            // Restore existing state
            number = this.getPersistedString( "0");
        } else {
            persistString( number);
        }
        try {
            currentIndex = Integer.parseInt(number);
        } catch( Exception e) {
            ; // skip any error, it will be corrected to 0
        }
    }

    @Override
    protected void onPrepareDialogBuilder(Builder builder) {   
        builder.setNegativeButton("Cancel", null);
        builder.setPositiveButton(null, null);
        iconName = getEntries();
        iconFile = getEntryValues();

        if (iconName == null || iconFile == null || iconName.length != iconFile.length) {
            throw new IllegalStateException(
                    "IconPickerPreference requires an entries array and an entryValues array which are both the same length");
        }

        icons = new ArrayList<IconItem>();
        for (int i = 0; i < iconName.length; i++) {
            IconItem item = new IconItem(iconName[i], iconFile[i], ( i == currentIndex));
            icons.add(item);
        }
        CustomListPreferenceAdapter customListPreferenceAdapter = new CustomListPreferenceAdapter(
                context, R.layout.preference_list_icon_picker, icons);
        builder.setAdapter(customListPreferenceAdapter, null);
    }
    private void updateIcon() {
        int identifier = resources.getIdentifier( selectedIconFile, "drawable", context.getPackageName());
        icon.setImageResource(identifier);
        icon.setTag(selectedIconFile);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在android中的ListPreference的项目中设置图标 的相关文章

随机推荐

  • LINQ to Entities 查询不支持转换为十进制

    我有一个数据库表事务 transactionID LocalAmount 其中 Localmount 属性的数据类型是float 在用户界面上我试图返回SUM按钮单击事件中一行中的列 Localamount 我用过decimal代替floa
  • 什么是“单位”? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 在单元测试的背景下 什么是 单元 我通常将其定义为单一代码执行路径通过单一方法 根据经验法则 测试一个方法所需的单元测试数量等于或大于
  • 透明 UINavigationBar 下的 UIWebView

    我有一个 UIWebView 我想将其放在半透明的 UINavigationBar 下 通常 当我将 UIScrollView 放在半透明的 UINavigationBar 下时 我会设置其 contentOffset 以便所有内容最初都会
  • API 端点返回“此请求的授权已被拒绝”。发送不记名令牌时

    我已按照教程使用 C 中的 OAuth 保护 Web API 我正在做一些测试 到目前为止我已经能够成功地从 token 我正在使用名为 Advanced REST Client 的 Chrome 扩展来测试它 access token t
  • 是否可以向 networkx 中的图形对象添加无向和有向边?

    我正在致力于实现一种算法来确定数据集的图形结构 数据集的变量之间可以有无向或有向边 我可以用 Python 创建自己的图形对象 但我很好奇 Networkx 是否具有此功能 据我所知 Networkx 只有一个 Graph 对象 仅无向边
  • Windows 身份验证和 Angular 7 应用程序

    我开发了内联网应用 后端 ASP NET WEB API 2 所有控制器都有授权属性 前端 Angular 7 产品构建后 我将生成的脚本移至后端项目
  • asyncio as_yielded 来自异步生成器

    我希望能够从许多异步协程中产生收益 异步的as completed有点接近我正在寻找的东西 即我希望任何协程能够随时返回调用者然后继续 但这似乎只允许常规协程具有单个返回 这是我到目前为止所拥有的 import asyncio async
  • 没有数学模块的Python 3中的ceil和floor等效吗?

    我需要在不使用的情况下将天花板和地板 3 2 结果 1 5 import math math floor 3 2 gt 3 2 math ceil 3 2 gt 好的 问题是这样的 将所有数字相加 15 45 15 45 15 有 N 个项
  • 读取虚拟端口时 ser.inWaiting() 始终返回 0

    我很难获得pyserial和一个玩得很好虚拟端口 我知道这是其他一些人写过的领域 但我在这些答案中找不到任何可以解决我的问题的内容 如果我只是太笨了 请原谅我 解决方案在其他地方已经存在 这就是我想要实现的目标 我想设置一个虚拟端口 我可以
  • Eclipse JUnit4:使用名称模式排除测试

    是否可以在 Eclipse 的 JUnit Run 配置中指定一个名称模式 例如 integration Test 在运行项目的所有测试时应将其从测试运行中排除 查看运行 调试配置中的选项 我认为这个问题可以简化为 是否可以排除基于 jun
  • 从 vb.net 运行 Python 函数

    我是 vb net 新手 我试图从 vb net 调用 python 函数 但收到错误 Invoke 不是 Microsoft Scripting Hosting ObjectOperations 的成员 Imports Microsoft
  • 如何在 firebase 中查询所有子项中具有特定值的属性

    我有这个数据结构 其中待办事项被组织为遵循路径 todos uid metausers simplelogin 1 displayName John Doe provider password provider id 1 simplelog
  • 在 Internet Explorer 中使用 .append() 刷新列表框的内容

    使用 Firefox 和 Chrome 上的 jQuery 我可以动态更改列表框中的数据 append 声明或我需要的任何方式 相同的代码不适用于 IE 列表框
  • 冻结 linq IQueryable (如 ToList().AsQueryable() 所做的那样)

    有没有办法冻结IQueryable这样在访问数据库时就不会向查询添加额外的连接 例如 我可以做一个 ToList 冻结查询 但这会对性能产生影响 因为我所做的任何过滤都是在中间层上进行的 并且我没有从数据库服务器上的预过滤中获得任何性能提升
  • 将其使用的代码和只读数据放在一起是个好主意吗?

    在编写与查找表相关的答案时另一个问题 https stackoverflow com q 41529921 149138我想起了我一直想知道的一件事 将函数所需的少量非代码数据放在函数旁边 而不是像传统的那样将其放在另一个部分中 这是否明智
  • Facebook 分享对话框图像不显示

    我正在使用 Facebook 共享对话框 https developers facebook com docs reference plugins share links https developers facebook com docs
  • 将 MP3 裁剪到前 30 秒

    原始问题 我希望能够从现有的 MP3 文件生成一个新的 完全有效的 MP3 文件以用作预览 先试后买的风格 新文件应该只包含第一个n轨道的秒数 现在 我知道我可以 砍流 n交付文件时的秒数 根据比特率和标头大小计算 但这有点脏 而且是 VB
  • 为什么它不能在 Swift 2 的 Playground 中显示任何内容?

    我尝试使用 spriteKit 在助理编辑器的游乐场中显示一些内容 然而 什么也没有显示 下面是代码 如果有人可以显示结果 蓝色矩形 请通知我 如果不是 请找出问题出在哪里 import UIKit import SpriteKit let
  • (HTML) 单击时下载 PDF 文件,而不是在浏览器中打开它们

    我想知道如何使 PDF 文件链接可下载而不是在浏览器中打开它们 这是如何在 html 中完成的 我假设它是通过 javascript 或其他东西完成的 有了html5 现在就可以了 在元素中设置 下载 属性 a href http link
  • 如何在android中的ListPreference的项目中设置图标

    我想将图标设置为ListPreferenceAndroid 中的项目 写什么内容ListPreference或者在哪里写来设置列表项图标 当您需要多次使用带有文本 图标的列表首选项时 您可以使用此解决方案 该版本很大程度上基于卢卡扎尼尼的好