Rasulbek Abdurasulov
Rasulbek Abdurasulov

Reputation: 111

Android textView size is bigger than dynamically created one

I got some issue with dynamically created TextViews. To be more specific:

                    <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Some text"
                    android:textColor="@color/black"
                    android:textSize="30px" />

appears much larger than:

            TextView prName = new TextView(this);
            prName.setTextColor(getResources().getColor(R.color.black));
            prName.setText("Some text");
            prName.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);

How to made them equal? Thanks beforehand

Upvotes: 0

Views: 886

Answers (5)

Rishabh Agrawal
Rishabh Agrawal

Reputation: 2106

Remove this line:

prName.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);

... or use this instead:

prName.setTextSize(30);

Upvotes: 0

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75778

use setTextSize(int unit, float size)

TypedValue.COMPLEX_UNIT_PX   //Pixels

TypedValue.COMPLEX_UNIT_SP   //Scaled Pixels

TypedValue.COMPLEX_UNIT_DIP  //Device Independent Pixels

In here just set

prName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

Upvotes: 0

Hussein El Feky
Hussein El Feky

Reputation: 6707

Make sure when you setTextSize for any type of view, you should set it in scalable points (sp) and not in pixels (px) like this:

In xml:

android:textSize="18sp"

In code:

prName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

Using scalable points will let your TextView text size be equal on all devices, while using pixels will let your TextView text size be unequal on devices with different resolutions.

Upvotes: 1

dn_c
dn_c

Reputation: 614

Set height and width as wrap_content for your textview.

LinearLayout.LayoutParams Params1 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
prName.setLayoutParams(Params1);

Upvotes: 1

Thomas R.
Thomas R.

Reputation: 8073

For text you should use scale points (SP) instead of pixel.

For xml:

 android:textSize="30sp"

For code:

 prName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);

Upvotes: 2

Related Questions