views:

47

answers:

1

Hi,

I think the answer to this question is probably so simple, but I'm struggling....

I have a TableLayout with multiple columns. I want the last column to be of a fixed width, but I want to define that width to just be able to hold the widest possible string from my program. i.e. it is always wide enough to contain "THIS STRING" without wrapping, or wasting any space.

I would like to do this as I have these TableLayouts within a ListView, so it looks very poor when the last column is of variable widths.

I have tried obtaining the string width, even going so far as to put it into a TextView, call getTextSize() then setWidth() on all appropriate TextViews. The problem I hit there is that gettextSize() returns pixels, but setWidth uses ScaledPixels.

I'm sure there is a really simple solution. Can anyone help?

+1  A: 

Are you using android:width="wrap_content" in your XML layout to define the width of that last column?

Edit: I think I just understood, you have a list view, that holds a table and you want all rows of the list view to have the same length for the last row of the table. Right?

I can only think of one, very unelegant solution right now and it involves going over all strings before building the list view.

The general logic would be as follows:

Im going to suppose you are getting al strings from an array, lets call it data.

Establish a global float variable to represent the longest string you have, lets call it maxLength.

Create a textview (lets call it invisibleText) in your layout that wont be visible, you can do this by setting

android:visibility="gone"

Then:

int size = data.length;
maxLength = 0.0f;
for(int i = 0;i<size;i++){
   invisibleText.setText(data[i]);
   float thisLength = invisibleText.getTextSize();
   if(thisLength>maxLength) maxLength = thisLength;
}

In you list view constructor:

TextView text = (TextView)findViewById(R.id.the_text_view_you_want);
text.setText(data[position]);
text.setWidth(maxLength)

The table columns should use android:width="wrap_content" I didnt test this code, but it should work, i've done similar stuff before.

blindstuff
Yes I am using android:width="wrap_content" for the last column, and yes I do want the last row of the table to have the same length in all entries in the listView, and would like that width to be just big enough to hold the maximum length string defined in the app.
Added some stuff to the answer. Try it out.
blindstuff