我有一个RelativeLayout
,其中包含ConstraintLayout
(和其他一些内容),我会以编程方式填写儿童。在初始化所有子视图后,我很难调整父RelativeLayout
的大小。
基本上我想要实现的是:
以下是代码段:
@BindView(R.id.session_summary_items_include_correct) View mCardCorrect;
//...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_session_summary_items, container, false);
ButterKnife.bind(this, view);
correctCard = new IncludedCard();
ButterKnife.bind(correctCard, mCardCorrect);
initializeViews();
mCardCorrect.post(() -> resizeView(mCardCorrect));
return view;
}
private void initializeViews(){
ArrayList<MyClass> items = MyClass.GetItems();
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (items.size() > 0){
correctCard.mCardTitle.setText("Correct Card");
ArrayList<View> views = getItemViews(items, layoutInflater);
populateLayoutWithItemViews(correctCard.mConstraintLayout, views);
}
}
private ArrayList<View> getItemViews(ArrayList<MyClass> items, LayoutInflater inflater){
ArrayList<View> results = new ArrayList<>();
for (MyClass item : items){
View view = inflater.inflate(R.layout.item_view, null);
TextView mTextTitle = (TextView) view.findViewById(R.id.item_view_title);
mTextTitle .setText(item.getTitle());
results.add(view);
}
return results;
}
private void populateLayoutWithItemViews(ConstraintLayout layout, ArrayList<View> items){
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(layout);
for (int idx = 0; idx < items.size(); idx ++){
View item = items.get(idx);
item.setId(View.generateViewId());
layout.addView(item);
// constraintSet magic to make them connect as expected
}
constraintSet.applyTo(layout);
}
private void resizeView(View view){
view.setLayoutParams(new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
static class IncludedCard{
@BindView(R.id.card_title) TextView mCardTitle;
@BindView(R.id.card_layout) ConstraintLayout mConstraintLayout;
}
现在,问题在于无论何时何地,无论何时我测量/调整mCardCorrect视图的大小,结果都是相同的:它将被测量到卡片标题,就好像里面的子项一样ConstraintLayout不存在。像这样:
我已尝试将测量/调整大小发布到Runnable,例如:FrameLayout child view not updating correctly on resize ,并使用OnGlobalLayoutListener,如:Android: set view height via ViewTreeObserver 。我还是一个Android新手,这是我的第一个项目,所以任何帮助都将不胜感激。谢谢!
答案 0 :(得分:0)
您需要约束每个视图。来自"Build a Responsive UI with ConstraintLayout":
...如果在设备上运行布局时视图没有约束,则会在位置[0,0](左上角)处绘制。
您添加的所有视图都不受约束,因此它们在(0,0)处彼此重叠。
看起来您正确设置了ConstraintSet
,您只需要使用ConstraintSet
添加约束。网上有一些很好的教程,演示了如何做到这一点。 Here就是一个。您也可以参考official documenation。