There is a TextView
of a certain size and whenever text set to it is too long I\'d like to re-set it to some preset value.
To accomplish this I am overr
This is my idea:
You can measure the text trivially with .length()
if its length is bigger than your desired limit, than cut put only the substring. But if you want to display entire text you can implement onClickListener()
on that TextView
which envoking will show entire text as Dialog
or whatever.
Another approach which I think can be suitable is to create different layouts for different density screens and then add in your xml android:maxLines="your limit"
android:textSize="some value"
and android:maxLength="@integer/mylimit"
(different limit and size for different density). So what remains is to measure the length and only show the substring (or default text)
Something like:
String myText = "bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla";
String clickForMore="...Click for more";
int limit = myActivity.this.getResources().getInteger(R.integer.limit); //dont forget to declare it in your string.xml
Imagine we have 3 lines of text and we permitted only 2 (with total length value of int limit
). Slice of our text fits inside the TextView
, but it is not entirely shown. We need to inform the user that there is more to read...
myTextView.setVisibility(View.INVISIBLE);// <--- takes the space in the container
if(clickForMore.length() < myText.length() && myText.length() > limit)// <--- avoiding negative place and checking if the entire text is inside the box or there are characters leftover.
{
String temp = myText.substring(0, limit-clickForMore.length());// <-- we cutting space from currently displayed (not original string) to append the `clickForMore` string information.
myTextView.setText(temp+clickForMore);
myTextView.setVisibility(View.VISIBLE);
myTextView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// display the dialog with full text....
return false;
}
}); //<--- instantiate the click listener
}
else
{
//the text fits the box and no need to slice it, just display it straight forward
}
myText.length() > limit
- Test whether the string overlaps the limit.
Implement .addTextChangeListener()
(TextWatcher
) and in afterTextChange()
override method implement all these I mentioned above.
Then you create onClickListener()
for the TextView
where you make dialog and then show your text as it is.
I hope you find this idea, reasonable. If you need more explanation what I had in mind feel free to write me.