如何在edittext中更改所选文本的背景颜色?

时间:2016-05-09 09:08:52

标签: android textview

如何在textview或edittext中选择部分文字,并在触摸按钮时更改所选文字的背景颜色?

我想模拟一个标记。 enter image description here

   public class BookViewActivity extends AppCompatActivity {
    Spannable str;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);

        // Get our EditText object.
        final EditText vw = (EditText)findViewById(R.id.text);
        Button bt=(Button)findViewById(R.id.button);

// Set the EditText's text.
        vw.setText("Italic, highlighted, bold.");

// If this were just a TextView, we could do:
// vw.setText("Italic, highlighted, bold.", TextView.BufferType.SPANNABLE);
// to force it to use Spannable storage so styles can be attached.
// Or we could specify that in the XML.

// Get the EditText's internal text storage
        str = vw.getText();
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                str.setSpan(new BackgroundColorSpan(0xFFFFFF00), vw.getSelectionStart(), vw.getSelectionEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        });

0 个答案:

没有答案