Im trying to have a search function for a text view that shows a large text so when ever the user enters a word the word would be highlighted inside the text view and my code does work with english but not with persian.
my highlighting method
public void setHighLightedText(TextView tv, String textToHighlight) {
String tvt = tv.getText().toString();
int ofe = tvt.indexOf(textToHighlight, 0);
Spannable wordToSpan = new SpannableString(tv.getText());
for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
ofe = tvt.indexOf(textToHighlight, ofs);
if (ofe == -1)
break;
else {
// set color here
wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
}
}
}
my TextView source
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void GetText(int rawRes) {
InputStream inputStream = null;
try {
inputStream = getResources().openRawResource(rawRes);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
resultString = byteArrayOutputStream.toString();
}
and my onCreate
et = (EditText) findViewById(R.id.et);
tv = (TextView) findViewById(R.id.tv);
GetText(R.raw.largetext);
tv.setText(resultString);
next = (Button) findViewById(R.id.button1);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setHighLightedText(tv,et.getText().toString());
}
});
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.AboutUs">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/et"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="find"
android:id="@+id/button1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
</LinearLayout>
Main text
```لورم ایپسوم یا طرحنما (به انگلیسی: Lorem ipsum) به متنی آزمایشی و بیمعنی در صنعت چاپ، صفحهآرایی و طراحی گرافیک گفته میشود. طراح گرافیک از این متن به عنوان عنصری از ترکیب بندی برای پر کردن صفحه و ارایه اولیه شکل ظاهری و کلی طرح سفارش گرفته شده استفاده می نماید
phrase i want to search
لورم