Android AlertDialog 主题选择实现 - 使用 R.array.colors

本示例展示如何在 Android 应用中使用 AlertDialog 实现主题选择功能,并利用 R.array.colors 资源存储颜色选项。用户可以选择不同的颜色主题,并通过 recreate() 方法立即生效。

public void AppTheme_b_or_w(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppTheme);
    builder.setTitle('选择主题颜色')
            .setSingleChoiceItems(R.array.colors, -1, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // 根据选中的which值设置主题颜色
                    switch (which) {
                        case 0:
                            setTheme(R.style.AppTheme_Night);
                            recreate();// 设置为浅色主题
                            break;
                        case 1:
                            setTheme(R.style.AppTheme);
                            recreate();// 设置为默认主题
                            break;
                    }
                }
            })
            .setPositiveButton('确定', new DialogInterface.OnClickListener() {
                
                public void onClick(DialogInterface dialog, int which) {
                    // 确定按钮点击事件
                    Snackbar.make(view, '下载按钮.ing', Snackbar.LENGTH_LONG)
                            .setAction('Action', null).show();
                }
            })
            .setNegativeButton('取消', new DialogInterface.OnClickListener() {
                
                public void onClick(DialogInterface dialog, int which) {
                    // 取消按钮点击事件
                    dialog.dismiss();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();
}

R.array.colors 的作用

R.array.colors 用于存储一个包含颜色选项的数组,这些选项可以在 AlertDialog 中显示,允许用户选择应用的主题颜色。该数组可以在字符串资源文件 (strings.xml) 中定义,并在 AlertDialog.Builder 的 setSingleChoiceItems() 方法中使用其资源 ID (R.array.colors) 进行引用。

例如,在 strings.xml 中定义一个包含颜色选项的数组:

<resources>
    <string-array name="colors">
        <item>浅色</item>
        <item>深色</item>
    </string-array>
</resources>

然后在代码中使用 R.array.colors 引用该数组。

此示例提供了一个简单的 Android 主题选择实现,展示了如何使用 AlertDialog 和 R.array.colors 资源来为用户提供灵活的主题定制选项。

Android AlertDialog 主题选择实现 - 使用 R.array.colors

原文地址: https://www.cveoy.top/t/topic/iQBZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录