2017-06-25 170 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。我只是试了一下,它工作正常。我不能说为什么左右不行。