You can first set you string content into the TextView
and then use setCustomSelectionActionModeCallback(...)
to intercept the selection within the TextView.
In the example bellow a selected word will be surrounded by <strong>...</strong>
.
For example selecting "testing" will make the following string visible into the TextView.
hello this is android testing android bla bla android bla bla android bla
Then selecting the last instance on "android" in the already transformed TextView content will make the following string visible into the TextVIew.
hello this is android testing android bla bla android bla bla android bla
Code :
public class MainActivity extends AppCompatActivity {
String yourString = "<p>hello this is android testing android bla bla android bla bla android bla</p>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.opening_today);
tv.setText(Html.fromHtml(yourString));
tv.setCustomSelectionActionModeCallback(new CallbackListener(tv));
}
class CallbackListener implements ActionMode.Callback{
private TextView tv;
private String strongS = "<strong>";
private String strongE = "</strong>";
public CallbackListener(TextView tv) {
this.tv = tv;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
int start = tv.getSelectionStart();
int end = tv.getSelectionEnd();
if( start == 0 && end == 0)
return false;
String content = tv.getText().toString();
String token = content.substring(start, end);
String before = content.substring(0, start);
String after = content.substring(end, content.length());
content = makeItStrong(before, after, token);
tv.setText(Html.fromHtml(content));
return false;
}
private String makeItStrong(String before, String after, String token){
return cleanTags(before, strongS, strongE) + strongS + token + strongE + cleanTags(after, strongS, strongE);
}
private String cleanTags(String source, String... exp){
for(String s: exp){
source = source.replace(s, "");
}
return source;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return true; }
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
@Override
public void onDestroyActionMode(ActionMode mode) {}
}
}