容器是一个线性布局,
<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/