Android Get length of highlighted text in TextView -
i'm doing app has textview , that's clickable. when clicked allows user select words or whole sentence or paragraph. got part of selecting , highlighting text, problem want have different colour highlight , save highlighted text db next time user check it, he/she see highlighted text.
so far i've tried:
tv.setonlongclicklistener(new onlongclicklistener() { @override public boolean onlongclick(view v) { int startselection = tv.getselectionstart(); int endselection = tv.getselectionend(); string selectedtext = tv.gettext().tostring().substring(startselection, endselection); log.e("text", "" + selectedtext); spannablestring spannable = new spannablestring(tv.gettext().tostring()); //spannable spannable = new spannablestring(tv.gettext().tostring()); spannable.setspan(new backgroundcolorspan(color.blue), startselection, endselection, 0); //tv.setselection(startselection, endselection); tv.settext(spannable); return true; } });
layout.xml:
<textview android:textstyle="bold" android:id="@+id/tvordinancetitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/app_name" android:textisselectable="true" />
any ideas or workaround? gladly appreciate help. thanks.
to change text color, use foregroundcolorspan
:
spannable.setspan(new foregroundcolorspan(color.red), startselection, endselection, 0);
to keep text color change selected text color, use selector: define xml under drawable -- text_color_selector.xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="@color/red" /> <item android:color="@color/black" /> </selector>
and use selector when styling textview in layout xml:
android:textcolor="@drawable/text_color_selector"
if want save selected text doing:
string selectedtext = v.gettext().tostring().substring(startselection, endselection);
Comments
Post a Comment