android - 如何通过代码添加分隔 View

标签 android

容器是一个线性布局,

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

在代码中,我尝试将 View 添加为:

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" />

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

如何在向线性布局添加 View 时使此分隔线可见?

为什么当我们通过 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);

关于android - 如何通过代码添加分隔 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42284290/

相关文章:

android - 如何使带有自定义背景图像的按钮在Android中显示点击动画

Android:暂时禁用 Activity 中的方向更改

android - JobService 的 onStartJob 方法在作业被安排后立即执行

java - 如何检查 Json 对象中是否存在键并获取其值

android - 在android xml中获取透明椭圆形下方的阴影

调用 getDrawable() 时出现 java.lang.OutOfMemoryError

android - 我可以使用 Firebase 存储进行在线音乐流式传输吗?

android - 最好使用 Cursor 适配器或 Array 适配器

android - 在 Android 上跟随动画

android - 对 Android CardView 的顶部部分进行颜色处理,同时保持圆角