我想基於某些條件以編程方式刪除和添加約束條件。以下是截圖:在ConstraintLayout中以編程方式刪除/添加約束條件
,我想刪除它這樣,但代碼:
所以在想同樣的效果達到編程
這裏是我試過的代碼:
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
編輯
我tried usingConstraintSet
還,但結果卻是,即使不同不知我的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);
看看這有助於https://stackoverflow.com/questions/5107740/how-do-i-programmatically-remove-an-existing-rule-that-was-defined-in-xml –
@ValdioVeliu對不起,但這是爲RelativeLayout PARAMS,我需要從constraintLayoutParams。 –
你有沒有打擾過谷歌,甚至看看API?這個答案不完全是你正在尋找,但應該給你一個想法https://stackoverflow.com/questions/41666566/constraintlayout-how-to-add-several-views-programmatically?rq=1 – Chisko