Android How to get selected word in Edittext?

前端 未结 2 410
星月不相逢
星月不相逢 2021-01-18 08:58

I am developing an app like Notepad in which I want to change the selected text formatting dynamically (colors, changing font styles, bold, italic, underline etc.) How can I

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 09:27

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

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

    Then you can apply your specific formatting by using this selected substring in the full string after taking it to a SpannableStringBuilder on a button click/some other 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);    
    

    Reference.

提交回复
热议问题