Android ListPreference摘要中的斜体文本

时间:2014-04-17 12:07:18

标签: android preferences listpreference edittextpreference

我正在创建一个具有少量EditTextPreferenceListPreference属性的首选项屏幕。我想要显示摘要文本&#34; 未设置&#34;何时未设置首选项。使用etp.setSummary(Html.fromHtml("<i> not set </i>")适用于EditTextPreference个属性,但lp.setSummary(Html.fromHtml("<i> not set </i>")不适用于ListPreference属性。文字&#34;未设置&#34;显示但不是斜体。

我尝试使用以下内容格式化摘要:

ListPreference lp = (ListPreference)findPreference("def_list_pref");
SpannableString str = SpannableString.valueOf("not set");
str.setSpan(new StyleSpan(Typeface.ITALIC), 0, str.length(), 0);
lp.setSummary(str);

我还尝试手动将preference.xml中的摘要设置为android:summary="<i> not set </i>"的ListPreference属性,但这也没有效果。

有没有人知道我可能做错了什么,或者这是ListPreference的错误?

感谢。

2 个答案:

答案 0 :(得分:0)

public class SpannedSummaryListPreference extends ListPreference {

    private CharSequence mCharSequenceSummary;

    public SpannedSummaryListPreference(Context context) {
        this(context,null);
    }

    public SpannedSummaryListPreference(final Context context, final AttributeSet attrs) {
        super(context,attrs);
        mCharSequenceSummary = getSummary();
    }

    @Override
    public CharSequence getSummary() {
        final CharSequence entry = getEntry();
        if (super.getSummary() == null || entry == null) {
            return super.getSummary();
        } else {
            if (mCharSequenceSummary instanceof String) {
                return super.getSummary();
            } else {
                return mCharSequenceSummary;
            }
        }
    }

    @Override
    public void setSummary(CharSequence summary) {
        super.setSummary(summary);
        mCharSequenceSummary = summary;
    }
}`

编辑:Kotlin解决方案:

class ListPreferenceEx @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs) {
    private var mCharSequenceSummary: CharSequence? = null

    init {
        mCharSequenceSummary = summary
    }

    override fun getSummary(): CharSequence? {
        val entry = entry
        val superSummary = super.getSummary()
        return if (superSummary == null || entry == null || mCharSequenceSummary is String)
            superSummary
        else
            mCharSequenceSummary
    }

    override fun setSummary(summary: CharSequence) {
        super.setSummary(summary)
        mCharSequenceSummary = summary
    }
}

答案 1 :(得分:0)

使用Context#getText(int resId)以编程方式在您的“首选项”上设置摘要文本:

findPreference("my_pref").setSummary(getText(R.string.settings_network_summary));

您的字符串资源格式如下

<string name="html_string" ><u>underline</u> <i>italic</i> <b>bold</b></string>