What units are applied when declaring a view programmatically?

Daniel Reyhanian :

When adding a view in an axml file, it is possible to simply specify the size and the units of the view's attribute, for example:

<TextView
    android:TextSize = "10sp"
    android:layout_marginTop = "10dp" />

As said in this answer, there are specific units for specific purposes.

My main question is, when applying a size programmatically (by code) in a dynamic way, what are the units applied for the size?

For example, when declaring a TextSize like this:

TextView tv = new TextView();
tv.TextSize = 10;

What are the units applied for the text size? sp? dp? px?

And most importantly, how can I change them to fit my needs?

Arpit bandil :

Hi @Daniel if u programmatically generate textview as following code

TextView tv = new TextView();
tv.setTextSize(10); // Sets text in sp (Scaled Pixel).

And if you want to set text size with other unit so you can achieved by following way.

TextView tv = new TextView();
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 10); // Sets text in px (Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); // Sets text in dip (Device Independent Pixels).
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); // Sets text in sp (Scaled Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10); // Sets text in pt (Points).
tv.setTextSize(TypedValue.COMPLEX_UNIT_IN, 10); // Sets text in in (inches).
tv.setTextSize(TypedValue.COMPLEX_UNIT_MM, 10); // Sets text in mm (millimeters).

By default Android uses "sp" for text size and "px" for view size.

For other View sizes we can set in px(pixels) but if you want customize the unit you can use custom methods

/**
     * Converts dip to px.
     *
     * @param context -  Context of calling class.
     * @param dip     - Value in dip to convert.
     * @return - Converted px value.
     */
    public static int convertDipToPixels(Context context, int dip) {
        if (context == null)
            return 0;
        Resources resources = context.getResources();
        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics());
        return (int) px;
    }

From above method you can convert YOUR_DESIRED_UNIT in pixels and then set to view. You can replace

TypedValue.COMPLEX_UNIT_DIP

with above unit as per you use case. You can also use it vice-versa for px to dip but we cant assign to custom unit to view so that's why i am using it like this.

I hope i explained well this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90808&siteId=1