Add padding on view programmatically

Leem.fin picture Leem.fin · Mar 13, 2012 · Viewed 267.4k times · Source

I am deveoping 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 ??

Answer

Jave picture Jave · Mar 13, 2012

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);