Showing posts with label textview. Show all posts
Showing posts with label textview. Show all posts

10 November 2010

TextView and MaxLines

I have a TextView (who doesn't?) and I want to adjust its height automatically, depending on the length of the text it will contain. Should be easy. It was, but it took me a couple of minutes to figure it out.

So I want my TextView to be by default one line tall, but be able to expand up to two lines. My initial set up was to set lines=1 and maxLines=2, but it was making the TextView always two lines. Not what I wanted! I went through the documentation again, read each word carefully, and then:
<TextView android:id="@+id/title"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:ellipsize="end"
android:maxLines="2"
android:minLines="1"
android:text="This is the text" />
So it turned out that you have to set both minLines and maxLines. TADA!

07 September 2010

Quick string resource formatting

Sooner or later, you would want to display a message to your user with dynamic content. This may be the number of results, the user's name, etc.

Luckily for us, Android provides a convenience method that we can use for such purposes.
public final String getString (int resId, Object... formatArgs)
This means that we can define a string in our strings.xml file with format specifiers supported by Java's formatter class. For example, if I have such a string:
<string name="formatted_string">Hello, %s! You have %d messages.</string>
I can get this string, apply the formatting, and then set it into a TextView without additional processing on my part.
TextView string = (TextView) findViewById(R.id.form_string);
string.setText(getString(R.string.formatted_string, "Zarah", 4));
And I will have this:
Nifty and easy!

Of course, this is a simple example. But I hope you get the drift. Do read the Formatter's documentation to see all possible formats you can use.