Ok, I have an EditText
, A Search Button
And A Textview
with a large scrollable text.
When I enter a word in EditText
and press the Search Button
, the word gets highlighted.Till this, it all works fine.
But what I want is that when I enter a word and press the button
, it should highlight the word and also move the camera to that particular word ( I think its called focusing in android), I don't want to scroll every time to find my highlighted word.Say my typed word is at the bottom of the text and is highlighted, I can't scroll it every time to find it, it's very irritating.So please help!
So what I want is that when I search for a word it should get highlighted and should also appear on the screen automatically without me scrolling down or up.
And One More thing, I want to unhighlight the word as soon as EditText becomes empty
Here Is My Code
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.xeoh.android.texthighlighter.TextHighlighter;
public class MainActivity extends AppCompatActivity {
EditText search;
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText)findViewById(R.id.search);
textView = (TextView) findViewById(R.id.text);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new TextHighlighter()
.setBackgroundColor(Color.parseColor("#FFFF00"))
.setForegroundColor(Color.RED)
.addTarget(textView)
.highlight(search.getText().toString(),TextHighlighter.BASE_MATCHER);
}
});
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/search"
android:hint="Search"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"
android:id="@+id/button"/>
<TextView
android:layout_width="match_parent"
android:id="@+id/text"
android:textSize="25sp"
android:layout_height="wrap_content"
android:text="@string/test"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
Assuming you have:
Layout:
Then in your code:
where
longText
is some long text defined in yourstrings.xml
. You may want to apply some other style on your text (as I did with<font color='red'>
).It should do the job. I've tested it on android 8 (Oreo) and it worked fine.