我想根据某些条件以编程方式删除和添加约束。以下是截图:
我想像这样删除它,但在代码中:
所以想要以编程方式实现相同的效果
这是我尝试过的代码:
if (advertisements.size() > 0) { //my own condition
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) btnCreateAd.getLayoutParams();
layoutParams.topToBottom = R.id.imvEmpty; //the imageview that is in center of the view
btnCreateAd.setLayoutParams(layoutParams);
recyclerView.setVisibility(View.VISIBLE);
txvMyAdEmptyText.setVisibility(View.GONE);
imvEmpty.setVisibility(View.GONE);
adapter.setList(advertisements);
adapter.notifyDataSetChanged();
} else {
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) btnCreateAd.getLayoutParams();
layoutParams.topToBottom = -1; //here i am trying to remove top constraint but it doesn't work
btnCreateAd.setLayoutParams(layoutParams);
recyclerView.setVisibility(View.GONE);
txvMyAdEmptyText.setVisibility(View.VISIBLE);
imvEmpty.setVisibility(View.VISIBLE);
adapter.setList(new ArrayList<Advertisement>());
}
mConstraintView.invalidate(); //this is my constraint view
编辑
我也尝试过使用 ConstraintSet
,但结果甚至有所不同,我的 RecyclerView(设置为父视图的边界)正在消失
ConstraintSet set = new ConstraintSet();
set.clone(parentView);
if (advertisements.size() > 0) {
recyclerView.setVisibility(View.VISIBLE);
txvMyAdEmptyText.setVisibility(View.GONE);
imvEmpty.setVisibility(View.GONE);
adapter.setList(advertisements);
adapter.notifyDataSetChanged();
} else {
set.connect(btnCreateAd.getId(), ConstraintSet.TOP, imvEmpty.getId(), ConstraintSet.BOTTOM, 0);
recyclerView.setVisibility(View.GONE);
txvMyAdEmptyText.setVisibility(View.VISIBLE);
imvEmpty.setVisibility(View.VISIBLE);
adapter.setList(new ArrayList<Advertisement>());
}
set.connect(btnCreateAd.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
set.connect(btnCreateAd.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
set.connect(btnCreateAd.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
set.applyTo(parentView);