1

I have a ListView and each row is a RelativeLayout with 2 TextViews side-by-side (call them textViewLeft and textViewRight).

The textViewRight text can change between "xxxxxxx" and "yyy" (both different lengths). I want to set the textViewRight width to be able to fit the "xxxxxxx", and then if I change the text to "yyy", I DON'T want the textViewRight width to change.

I know that in my xml I can specify layout_width to a particular value, but devices have lots of different fonts. So is there a way that I can programmatically set the width of textViewwRight to ensure it always fits the string "xxxxxxx"?

Wise Shepherd
  • 2,228
  • 4
  • 31
  • 43

1 Answers1

-1

Well, there is no easy way to answer that, you could set the width through code, using the width available, you coul change the text size depending on the screensize, there are several different solutions.

It really depends on how you are handling your app, do you already have different layout folders? If so why not try some sizes that will work well for the intended range?

Either way, you should calculate it to fit the bigger text from the start and not change it when the text changes.

To be more specific. One solution would be to have the text on the Textview be xxxxxx, and have the layout's width in xml be "wrap_content". Now what you do is, get the view's width after it has been laid out, or else you get a 0 return.

One way to do exactly that is to add a viewtreeobserver to your TextView on your onCreate method:

    ViewTreeObserver vto = yourTextView.getViewTreeObserver();  
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  
        @Override  
        public void onGlobalLayout() {  
            this.yourTextView.getViewTreeObserver().removeGlobalOnLayoutListener(this);  
            int width  = layout.getMeasuredWidth(); 
            int height = layout.getMeasuredHeight();  
        }  
    });

Now you have the width, all you have to do is change the width to that fixed value, the following should work:

    yourTextView.getLayoutParams().width = theWidthYouGot;