如何通过代码添加分隔视图



容器是线性的,

<LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

在代码中,我试图添加视图为:

final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// add alpha view to container view
View alphaView = inflater.inflate(R.layout.item_info_alpha, null, false);
container.addView(alphaView);
// add divider view to container view
container.addView(inflater.inflate(R.layout.item_divider, null, false));
// add beta view to container view
View betaView = inflater.inflate(R.layout.item_info_beta, null, false);
container.addView(betaView);
// add divider view to container view
container.addView(inflater.inflate(R.layout.item_divider, null, false));

item_divider.xml

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:background="#F2F2F4" />

通过代码添加时不可见分隔线。

在为线性布局添加视图时,如何使此分隔线可见?

为什么当我们通过XML添加 view 时,它不会在linearlayout中添加?

您可以简单地做:

container.addView(inflater.inflate(R.layout.item_divider, null));

或尝试此代码:

        View view = new View(YOUR_CONTEXT); //getContext() for example
        int hight = 8;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, hight);
        view.setLayoutParams(params);
        view.setBackgroundColor(Color.parseColor("#F2F2F4"));
        container.addView(view);

true中的false替换CC_1,并且在LinearLayout上不明确调用addView(..)

LayoutInflater的目的是不必手动设置LayoutParams

如果将ViewattachToRoot=false充气,则使用root的LayoutParams来创建新的View,然后丢弃。

如果attachToRoot=true,则保留了LayoutParams,并且新的View也附加到rootview,在您的情况下,LinearLayout

最新更新