Reputation: 302
I have a android textview and I am setting 10 word sentence to it.
Now, I need to delete one word (say 4th word) without affecting the remaining word's positions/alignment.
Please refer below image. Also note, if am replacing that particular word with whitespaces, still alignment is slightly changing for remaining word's, as each character taking different width.
How can I achieve it using textview? Any help is much appreciated. Thanks.
Upvotes: 2
Views: 517
Reputation: 40898
Here is an algorithm
StaticLayout.getDesiredWidth()
for calculating the width of the word that you want to be hiddenLet's code:
Note: I used the same text as you put.
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is my sample text goes here\n with multiple words and lines and center aligned" />
Java
TextView textView = findViewById(R.id.textview);
String originalText = textView.getText().toString();
// Get the word that you want to replace
String text = originalText.substring(11, 18);
// Step 1: Get the word width
float wordWidth = StaticLayout.getDesiredWidth(text, new TextPaint());
// Step 2: Get the space width
float spaceWidth = StaticLayout.getDesiredWidth(" ", new TextPaint());
// Step 3: Get the needed no. of spaces
float nSpaces = wordWidth / spaceWidth;
// Step 4: Replace the word with the no. of spaces
StringBuilder newText = new StringBuilder(originalText.substring(0, 11));
for (int i = 0; i < nSpaces; i++) {
newText.append(" ");
}
newText.append(originalText.substring(18));
textView.setText(newText);
Result
Upvotes: 0
Reputation: 13019
You can use a SpannableString
to apply the color of the background (looks like white in your picture) to the letters which should vanish.
If you want to apply the effect to the fourth word ("sample") then you can write
val startOfWord = 11
val endOfWord = 16
val spannable = SpannableString(“This is my sample text goes ...”)
spannable.setSpan(ForegroundColorSpan(Color.WHITE),
startOfWord, endOfWord + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
exampleTextView.text = spannable
See also Spantastic text styling with Spans by Florina Muntenescu
Upvotes: 2