运营商" +"无法应用于android.text.SpannableString

时间:2015-07-04 12:51:18

标签: android spannablestring

enter code here我正在创建一个小型Android应用。我想在textview中显示一个文本,其中有多个部分可供点击。我正在使用android.text.SpannableString来达到这个目的。这是我的代码:

public class MainActivity extends ActionBarActivity {

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



        final Spannable sd = new SpannableString("Android Multiple clickable strings in textview");
        final ClickableSpan clickableSpan3 = new ClickableSpan() {


            @Override
            public void onClick(View textView) {
                Toast toast1 = Toast.makeText(getApplicationContext(), "first", Toast.LENGTH_SHORT);
                toast1.setGravity(Gravity.CENTER, 0, 0);
                toast1.show();
            }
        };
        final ClickableSpan clickableSpan4 = new ClickableSpan() {
            @Override
            public void onClick(View textView) {

                Toast toast2 = Toast.makeText(getApplicationContext(), "second", Toast.LENGTH_SHORT);
                toast2.setGravity(Gravity.CENTER, 0, 0);
                toast2.show();
            }

        };
        sd.setSpan(clickableSpan3, 8, 16, SPAN_POINT_POINT);
        sd.setSpan(clickableSpan4, 17, 26,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        TextView textView = (TextView) findViewById(R.id.hello);
        textView.setText(sd);
        textView.setMovementMethod(new LinkMovementMethod());


    }

它正常工作,但如果我更改代码以向TextView添加新单词

mTextView.setText(sd ** +" my words" **); mTextView.setMovementMethod(LinkMovementMethod.getInstance());

所有跨越的选择都会消失。如何避免呢?

1 个答案:

答案 0 :(得分:3)

使用TextUtils.concat(CharSequence... text)方法 来自文档:

  

返回连接指定CharSequences的CharSequence,   保留他们的跨度,如果有的话。

代码如下:

mTextView.setText(TextUtils.concat(sd,"my words"));