2

我正在创建一个具有一些 属性EditTextPreference的 首选项屏幕。ListPreference当未设置首选项时,我试图让摘要文本显示“未设置”。使用 etp.setSummary(Html.fromHtml("<i> not set </i>") 适用于 EditTextPreference 属性,但lp.setSummary(Html.fromHtml("<i> not set </i>") 不适用于 ListPreference 属性。显示文本“未设置”但不是斜体。

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

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 中为ListPreference 属性手动设置摘要, android:summary="<i> not set </i>" 但这也不起作用。

有谁知道我可能做错了什么,或者这是一个错误ListPreference

谢谢。

4

2 回答 2

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;
    }
}`

编辑:科特林解决方案:

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
    }
}
于 2018-04-09T10:18:54.240 回答
0

使用Context#getText(int resId)以编程方式在 Preference 上设置摘要文本:

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

您的字符串资源格式如下

<string name="html_string" ><u>underline</u> <i>italic</i> <b>bold</b></string>
于 2019-11-08T11:18:58.313 回答