问题描述
我正在开发 Android v2.2 应用.
I am developing Android v2.2 app.
我有一个 Fragment
.在片段类的 onCreateView(...)
回调中,我将布局膨胀到片段,如下所示:
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;
}
上面膨胀的布局文件是(login.xml):
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>
我想设置一个 paddingTop
到上面的 元素,我想在 Java 代码中做而不是在 xml 中进行.
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.
如何在我的片段 Java 类代码中将 paddingTop
设置为 ??
How to set paddingTop
to <LinearLayout>
in my fragment Java class code ??
推荐答案
view.setPadding(0,padding,0,0);
这会将顶部填充设置为 padding
-pixels.
This will set the top padding to padding
-pixels.
如果你想在 dp
中设置它,你可以做一个 转化:
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);
这篇关于以编程方式在视图上添加填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!