User42590
User42590

Reputation: 2521

Resize TextView Programmatically

I have a textView in my app . Now, I want to resize textView on click. I gave its max height and max width but it does not resize it and show the width and height defined in the layout. Any help would be appreciated

Here is my code:

 <TextView
        android:id="@+id/textView2"
        android:layout_width="30dp"
        android:layout_height="40dp"
        android:layout_gravity="fill_horizontal"
        android:layout_marginLeft="10dip"
        android:layout_marginTop="10dip"
        android:text="Hello"/>

Upvotes: 4

Views: 16502

Answers (4)

Permita
Permita

Reputation: 5493

you can use setMaxLines(int) to resize the TextView programmatically.

Upvotes: 0

Jonathan
Jonathan

Reputation: 3457

Logically why would the TextView resize when you change its max height and max width? What you've said is "TextView, you are 30dp x 40dp whether you like it or not". Then you come along and say "Oh by the way, if some day you can get more space, you can go all the way up to 40dp x 50dp, but for now you're still 30dp x 40dp". No matter how big you let the TextView be, it is still going to be 30dp x 40dp because you haven't told it to change its size, you've just changed how big it can possibly be.

If you want to change this behavior, what you need to do is say "Hey TextView, feel free to get as big as you want now that I've put these upper bounds on you". To do this, you would use LayoutParams as described above/shown below.

// set the max height
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

This also assumes that you want your max height/width to be your limiting factors. If you want to just say "Hey textView, be this size", Ajay's answer will do the trick.

Upvotes: 5

Ajay nath
Ajay nath

Reputation: 133

Check this out

TV= (TextView) findViewById(R.id.textView2);
TV.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       final LayoutParams lparams = new LayoutParams(50,30); // Width , height
       TV.setLayoutParams(lparams);
    }
});

Upvotes: 2

Naresh
Naresh

Reputation: 3179

You use LayoutParams in the code and set MATCH_PARENT for height and then add something like

textView.setLayoutParams(layoutParams);

Upvotes: 1

Related Questions