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

我有一个碎片。在我的片段类的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>

我想设置一个paddingTop到上面的<LinearLayout>元素,我想在Java代码中做,而不是在xml中做。

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


当前回答

当以编程方式填充时,通过将像素转换为Dp转换为密度相关的值。

其他回答

view.setPadding(0,填充,0,0);

这将设置顶部填充为padding-pixels。

如果你想在dp中设置它,你可以做一个转换:

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

您可以设置填充到您的视图通过程序语法贯穿下面的代码-

view.setPadding(0,1,20,3);

而且,也有不同类型的填充可用-

填充

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

这些链接将指向Android开发者站点。希望这对你有帮助。

步骤1:首先,将填充值作为一个整数。

int padding = getResources().getDimensionPixelOffset(r . dimension .padding);

或者int padding = 16;[使用任何方法]

步骤2:然后为布局分配填充值。

布局。setPadding(padding, padding, padding, padding);

布局。setPadding(padding_left, padding_top, padding_right, padding_bottom);

所有侧面不同的填充可以分配。布局。setPadding(16,10,8,12);

为了删除填充(无填充),设置填充值为0,

layout.setPadding(0, 0, 0, 0);

回答你的第二个问题:

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

就像SpK和Jave建议的那样,将以像素为单位设置填充。可以在dp中通过计算dp值进行设置,如下所示:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);
    binding.appBarMain.toolbar.setOnApplyWindowInsetsListener { _, insets ->
        val statusBarSize: Int =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                insets.getInsets(WindowInsets.Type.systemBars()).top
            } else {
                insets.systemWindowInsetTop
            }
        binding.appBarMain.appBarLayout.setPadding(0, statusBarSize, 0, 0)
        return@setOnApplyWindowInsetsListener insets
    }