为子视图分配边距

Assign margins to childviews

我正在膨胀一个只有 TextView 的视图。父视图是 LinearLayout。我的父视图如下所示:

        <LinearLayout
            android:id="@+id/posmSelectedBrandsLL"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            android:layout_below="@+id/brandPOSMspinner"/>

我的子视图如下所示:

<TextView
    android:id="@+id/chip12345"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/tag_background"
    android:text="TAG"
    android:layout_marginTop="50dp"
    android:paddingLeft="10dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingRight="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:textColor="@color/textcolorLogin"
    android:textSize="22sp" />

这就是我膨胀视图的方式:

        final LinearLayout editParentLL = (LinearLayout) findViewById(R.id.posmSelectedBrandsLL);
        final View editChildView = getLayoutInflater().inflate(R.layout.tag_layout, null);
        editParentLL.addView(editChildView);

        TextView tvChip = editChildView.findViewById(R.id.chip12345);
        tvChip.setText(p.getProductName());

然后出来的结果是这样的:

我想要的是把三个TextView分开。所以不是一个盒子,而是三个不同的盒子。

我需要你的帮助才能完成。 谢谢。

您应该使用 LayoutParams 来设置您的 editChildView 边距:

LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
editChildView.setLayoutParams(params);

更多详情请参考:https://android--code.blogspot.in/2015/05/android-textview-layout-margin.html

如果你需要一个一个的TextView,你必须使用like Orientation

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

试试这个

final View editChildView = getLayoutInflater().inflate(R.layout.view_add_item_with_details, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10,2,10,2);
        editChildView.setLayoutParams(layoutParams);
        editParentLL.addView(editChildView);

        TextView tvChip = editChildView.findViewById(R.id.chip12345);
        tvChip.setText(p.getProductName());

您可以在 .setMargin 方法中设置任何值