如何检测所选文本是否为粗体?

时间:2014-12-29 07:49:15

标签: android xamarin.android spannablestring

我正在Xamarin.Android中创建一个富文本框。到目前为止,我可以将所选文本转换为粗体或斜体文本。但是,现在我想,当点击粗体按钮时,所选文本应该恢复正常。所以我的问题是,如何检查所选文本是否为粗体?    我试过以下方式

 void bButton_Click(object sender, EventArgs e)
    {
        var richEditText = FindViewById<EditText>(Resource.Id.richEditText);


        SpannableStringBuilder sb = new SpannableStringBuilder(richEditText.Text);

        string selected = sb.SubSequenceFormatted(richEditText.SelectionStart, richEditText.SelectionEnd).ToString();

        if(selected == Android.Graphics.TypefaceStyle.Bold) // It,s not working.
        So please suggest  me how to check selected text is bold or not

        following line for to make bold

        sb.SetSpan(new StyleSpan(Android.Graphics.TypefaceStyle.Bold), richEditText.SelectionStart, richEditText.SelectionEnd,0);


        richEditText.TextFormatted = sb;

1 个答案:

答案 0 :(得分:0)

当然,您无法询问String对象是否为Enum

这样的工作:

button.Click += (sender, args) =>
{
    var start = editText.SelectionStart;
    var end = editText.SelectionEnd;

    if (start > end)
    {
        var temp = end;
        end = start;
        start = temp;
    }

    var ss = (ISpannable)editText.TextFormatted;

    // get all spannables in selection, there could be multiple
    var spans = ss.GetSpans(start, end, Java.Lang.Class.FromType(typeof(StyleSpan)));

    var exists = false;

    // loop over all spans
    foreach (var t in spans)
    {
        var style = ((StyleSpan)t).Style;

        // if one of the spans is bold
        if (style == TypefaceStyle.Bold)
        {
            // remove the span
            ss.RemoveSpan(t);
            exists = true;
        }
    }

    // if none of the spannables were bold, lets make it bold
    if (!exists)
        ss.SetSpan(new StyleSpan(TypefaceStyle.Bold), start, end, 0);
};

基本上我在上面的代码中所做的就是检查选择中的所有Spannable个实例,看看他们的Style是否为TypefaceStyle.Bold。虽然演员很天真,所以要小心。