3

我正在編寫自定義視圖,以便能夠使用自定義XML屬性根據這些屬性設置視圖的邊距和大小,一切正常,直到我到了ConstraintLayout得到他們的利潤和大小由自定義值決定。 邊距不會有任何區別,並且視圖保留在其父級ConstraintLayout的左上角。 可能是什麼問題? (圖像應該是從500PXs屏幕邊界的距離)以編程方式更改ConstraintLayout兒童的邊距和大小

if (hasCustomWidth || hasCustomHeight || hasCustomTopMargin || hasCustomRightMargin || hasCustomBottomMargin || hasCustomLeftMargin) { 
    if(((ViewGroup)getParent()) instanceof LinearLayout) { 
     LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight)); 
     ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) newLayoutParams; 
     marginLayoutParams.setMargins((int) Math.round(customLeftMargin), (int) Math.round(customTopMargin), (int) Math.round(customRightMargin), (int) Math.round(customBottomMargin)); 
     setLayoutParams(newLayoutParams); 
    } else if(((ViewGroup)getParent()) instanceof ConstraintLayout) { 
     ConstraintLayout parentConstraintLayout = (ConstraintLayout)CustomAppCompatImageView.this.getParent(); 

     ConstraintLayout.LayoutParams newLayoutParams = new ConstraintLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight)); 

     ConstraintSet constraintSet = new ConstraintSet(); 

     constraintSet.clone(parentConstraintLayout); 

     constraintSet.connect(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 500); 
     constraintSet.setMargin(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, 500); 

     setLayoutParams(newLayoutParams); 
     constraintSet.applyTo(parentConstraintLayout); 

     parentConstraintLayout.invalidate(); 
    } else { 
     throw new RuntimeException("no listed parent LayoutParams subclass!"); 
    } 

    invalidate(); 
} 

結果:

enter image description here

回答

3

我找到了解決辦法:很明顯Android不採取ConstraintSet.LEFTConstraintSet.RIGHT爲正確的參數,並且必須用ConstraintSet.STARTConstraintSet.END代替。

+1

是的,我有一個非常相似的情況,只有使用ConstraintSet.START和ConstraintSet才能正常工作.END –

+0

謝謝救了我的命。 –

相關問題