Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add padding on view programmatically

I am developing Android v2.2 app.

I have a Fragment. In the onCreateView(...) callback of my fragment class, I inflate an layout to the fragment like below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.login, null);
        
    return view;
}

The above inflated layout file is (login.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

</LinearLayout>

I would like to set a paddingTop to the above <LinearLayout> element , and I want to do it in the Java code instead of do it in xml.

How to set paddingTop to <LinearLayout> in my fragment Java class code ??

like image 784
Leem.fin Avatar asked Oct 10 '22 01:10

Leem.fin


People also ask

How to add padding programmatically?

Programmatic approach Button btn = findViewById(R. id. btn_id); Use the setPadding(left, top, right, bottom) method on the view to set the padding.

What is padding in Android example?

The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific number of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge.

What is padding in layout?

Padding is the space inside the border, between the border and the actual view's content. Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent).


2 Answers

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);
like image 72
Jave Avatar answered Oct 12 '22 15:10

Jave


To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);

Hope that helps!

like image 41
Chris Avatar answered Oct 12 '22 14:10

Chris