2017-06-25 169 views
0

我想以編程方式更改togglebutton的約束,但我已經設置了xml文件中togglebutton的約束。我需要的是當我單擊切換按鈕時,我想重寫的切換按鈕,即,當我點擊togglebutton1約束然後用togglebutton3的左側添加自togglebutton2左側的約束與marging 0如何以編程方式更改約束佈局的子視圖的約束

private ToggleButton toggleButton1; 
private ToggleButton toggleButton2; 
private ToggleButton toggleButton3; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1); 
    toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2); 
    toggleButton3 = (ToggleButton) findViewById(R.id.toggleButton3); 

    CompoundButton.OnCheckedChangeListener compoundButton = new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) { 
       ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout); 
       ConstraintSet set = new ConstraintSet(); 
       set.clone(constraintLayout); 
       set.connect(toggleButton3.getId(),ConstraintSet.LEFT,toggleButton2.getId(),ConstraintSet.LEFT,0); 
       set.applyTo(constraintLayout); 
      } else 
       // somecode 
     } 
    }; 
    toggleButton1.setOnCheckedChangeListener(compoundButton); 
} 

希望有人能幫助我

+0

第二次刪除setContentView之後,它也不起作用。 –

+0

你想重繪佈局嗎? –

+0

我想重寫佈局中的togglebutton約束 –

回答

1

我沒有解決方案,但我可以告訴你一些讓我信服連接不起作用的東西g右/左,因爲它頂部/底部。將您的OnCheckedChangeListener代碼更改爲以下並運行它。

CompoundButton.OnCheckedChangeListener compoundButton = new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout); 
      ConstraintSet set = new ConstraintSet(); 
      set.clone(constraintLayout); 
      if (isChecked) { 
       set.connect(toggleButton3.getId(), ConstraintSet.LEFT, toggleButton2.getId(), ConstraintSet.LEFT, 0); 
      } else { 
       set.connect(toggleButton3.getId(), ConstraintSet.BOTTOM, toggleButton2.getId(), ConstraintSet.BOTTOM, 0); 
      } 
      set.applyTo(constraintLayout); 
     } 
    }; 

當您第一次單擊toggleButton1時,您將看不到更改。當你第二次點擊它時,你應該看到toggleButton3跳轉,所以它的底部與toggleButton2的底部對齊。 (確保它不與排隊開始。)

您的問題可能與this bug report有關。

如果您確實找到了解決方案,那麼您可以將其作爲答案發布在此處,因爲我已經多次運行該問題。

我希望有幫助。


編輯 這裏是你可以做什麼來解決這個問題。使用ConstraintSet.STARTConstraintSet.END而不是ConstraintSet.LEFTConstraintSet.RIGHT。我只是試了一下,它工作正常。我不能說爲什麼左右不行。