我正在开发Android v2.2应用程序.

我有Fragment英镑.在我的fragment类的onCreateView(...)回调中,我对该片段展开了一个布局,如下所示:

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

上面的布局文件是(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>

我想为上面的<LinearLayout>元素设置一个paddingTop,我想在Java代码中执行它,而不是在xml中执行它.

如何在我的片段Java类代码中将paddingTop设置为<LinearLayout>??

推荐答案

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

这会将顶部填充设置为padding像素.

如果您希望将其设置为dp,则可以执行conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

Android相关问答推荐

将动作传递给嵌套的可组合物

如何检测HitTest是否命中给定的网格对象?

如何从sqlite数据库中检索数据到碎片android?

在Jetpack Compose中实现自动换行

如何判断堆肥是否为空?

SmsMessage如何在Kotlin库中工作?

Android v31 及更低版本中 ImageView 中的圆角

如何在 kotlin 中接收带有和不带有可空对象的集合并保持引用相同

SQLite Kotlin 问题 - 没有数据库

如何在 Android 的 ViewModel 中使用 LiveData

在 kotlin 中动态添加 GridView

在Android RoomDB中使用Kotlin Flow和删除数据时如何解决错误?

视觉转换后获取文本

在 Jetpack Compose 中使用 .observeAsState() 时,如何在更改 MutableLiveData 的值后开始执行一段代码?

协程是否在 if 条件下保持秩序?

如何授予对 Uri 图像的永久权限(androidx)

如何在 Jetpack Compose 中填充矢量图像的背景?

操作系统会终止已启动的服务并调用Service.onDestroy吗?

Android YouTube SDK - 视频无法在某些 Android 设备中播放

如何让用户与任意应用程序共享文件?