如何在textview或edittext中选择部分文字,并在触摸按钮时更改所选文字的背景颜色?
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);
}
});