Android: TextView automatically truncate and replace last 3 char of String

Android: TextView automatically truncate and replace last 3 char of String

If you want to automatically truncate a TextView and replace the last three characters of a string in Android, you can achieve this by modifying the text before setting it to the TextView. Here's a sample code snippet that demonstrates how to do this:

import android.os.Bundle; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.textView); // Original text String originalText = "This is a sample text"; // Check if the original text has at least 3 characters if (originalText.length() >= 3) { // Truncate the last 3 characters String truncatedText = originalText.substring(0, originalText.length() - 3); // Replace the last 3 characters with "..." truncatedText += "..."; // Set the modified text to the TextView textView.setText(truncatedText); } else { // Handle the case when the original text is too short to truncate textView.setText(originalText); } } } 

In this code:

  1. We have a TextView named textView in an Android activity.

  2. We define the originalText string, which is the text you want to display.

  3. We check if the originalText has at least 3 characters. If it does, we truncate the last 3 characters using the substring() method and then append "..." to the truncated text.

  4. Finally, we set the modified text to the TextView. If the original text has fewer than 3 characters, we simply set the original text as is.

You can adapt this code to your specific use case by replacing originalText with the text you want to display in your TextView.


More Tags

podfile idisposable associative-array uicollectionviewcell gitlab-ci-runner userid lex odoo azure-keyvault contact-form-7

More Java Questions

More Investment Calculators

More Chemical thermodynamics Calculators

More Various Measurements Units Calculators

More Financial Calculators