如何从SpannableStringBuilder中删除第一个字符

时间:2018-10-25 10:17:22

标签: android string

  • 是否可以从中删除第一个字符 SpannableStringBuilder。

  • 类似于我们如何删除字符串中的第一个字符

  • 我也在尝试查找第一个字符是否为空格..是否有办法 做到

2 个答案:

答案 0 :(得分:0)

您可以使用子序列builder.subSequence(0, b.length())

答案 1 :(得分:0)

尝试一下

您可以使用spannableStringBuilder.delete()

示例代码

public class MainActivity extends AppCompatActivity {


    String startText = " this is demo";
    SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvText=findViewById(R.id.tvText);
        TextView tvText1=findViewById(R.id.tvText1);
        spannableStringBuilder = new SpannableStringBuilder(startText);

        StyleSpan firstStyleSpan = new StyleSpan(android.graphics.Typeface.BOLD);

        spannableStringBuilder.setSpan(firstStyleSpan, 0, spannableStringBuilder.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold

        tvText1.setText(spannableStringBuilder);

        // first check here that  first character of spannableStringBuilder is a space or not
        if(spannableStringBuilder.charAt(0)== ' ')
            spannableStringBuilder.delete(0,1); // using spannableStringBuilder.delete() remove that first space from your spannableStringBuilder

        tvText.setText(spannableStringBuilder);

        Log.e("RESULT",spannableStringBuilder.toString());

    }


}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/tvText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


</LinearLayout>

输出

  • 第一个textview显示文本包含SpannableStringBuilder开头的空格
  • textview删除空格后的第二个SpannableStringBuilder显示结果

enter image description here