Android How to get selected word in Edittext?

I am developing an application, such as Notepad, in which I want to dynamically change the selected text formatting (colors, font styles, bold, italics, underline, etc.). How can I format a specific word?

+6
source share
2 answers

You can get the selected word using the getSelectionStart() and getSelectionEnd() methods:

 EditText etx=(EditText)findViewById(R.id.editext); int startSelection=etx.getSelectionStart(); int endSelection=etx.getSelectionEnd(); String selectedText = etx.getText().substring(startSelection, endSelection); 

You can then apply your specific formatting using this selected substring in the full line after you go to SpannableStringBuilder when you press the / button in another event:

Code for formatting text:

  int startSelection=etx.getSelectionStart(); int endSelection=etx.getSelectionEnd(); final SpannableStringBuilder sb = new SpannableStringBuilder(etx.getText().toString()); final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold final StyleSpan iss = new StyleSpan(android.graphics.Typeface.ITALIC); // Span to make text italic sb.setSpan(iss, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE); sb.setSpan(bss, startSelection, endSelection, Spannable.SPAN_INCLUSIVE_INCLUSIVE); etx.setText(sb); 

Link

+3
source
 EditText et1=(EditText)findViewById(R.id.edit); int startSelection=et.getSelectionStart(); int endSelection=et.getSelectionEnd(); String selectedText = et1.getText().substring(startSelection, endSelection); 

Hope this code fits your case

0
source

Source: https://habr.com/ru/post/916077/


All Articles