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 format a specific word?
Asked
Active
Viewed 3,666 times
2 Answers
3
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);

Community
- 1
- 1

Imran Rana
- 11,899
- 7
- 45
- 51
-
@Imaran If user select some text at runtime than How can I know what is the "startSelection" and "endSelection" value? Can u give me suggestion for this? – Nik88 May 18 '12 at 10:53
-
1You are using `getSelectionStart()` and `getSelectionEnd();` method to get those value. So think there is a button namely **ITALIC**. After selecting the text user will click this button to get italic effect. Then you can get those value on the button click event like: `ITALIC.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int startSelection=etx.getSelectionStart(); int endSelection=etx.getSelectionEnd(); } });` – Imran Rana May 18 '12 at 10:59
-
1@Imaran. Thanks a lot for giving your time. Its working great. – Nik88 May 18 '12 at 11:02
0
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 suits yours case

Thiru VT
- 831
- 2
- 8
- 24