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 ??
Programmatic approach Button btn = findViewById(R. id. btn_id); Use the setPadding(left, top, right, bottom) method on the view to set the padding.
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.
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).
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With