以编程方式更改约束布局中的指南百分比

我有像这样的约束布局的指南

 

后来我想将app:layout_constraintGuide_percent值更改为其他条件。 我怎样才能做到这一点。

Solutions Collecting From Web of "以编程方式更改约束布局中的指南百分比"

有两种方法可以做到:

  • 使用ConstraintLayout.LayoutParams

此方法从ConstraintLayout获取特定参数并进行修改。

 Guideline guideLine = (Guideline) findViewById(R.id.your_guideline); ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideLine.getLayoutParams(); params.guidePercent = 0.45f; // 45% // range: 0 < -> 1 guideLine.setLayoutParams(params); 
  • 使用ConstraintSet

此方法包括克隆ConstraintLayout属性,修改它们然后应用于View

它很慢。

 ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.your_constraint_with_guideline); ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(constraintLayout); constraintSet.setGuidelinePercent(R.id.your_guideline, 0.07f); // 7% // range: 0 < -> 1 TransitionManager.beginDelayedTransition(constraintLayout); constraintSet.applyTo(constraintLayout); 

创建视差效果

为了测试这些方法,我使用GuideLineScrollView在顶部创建了一个视差animation。

AndroidManifest.xml ,在Activity ,添加: android:hardwareAccelerated="true"

   ... 

MainActivity.java

 Guideline guideTopInfo; ConstraintLayout constraintLayout; ConstraintLayout.LayoutParams params; ConstraintSet constraintSet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); guideTopInfo = (Guideline) findViewById(R.id.guideline2); constraintLayout = (ConstraintLayout) findViewById(R.id.constraint_root); params = (ConstraintLayout.LayoutParams) guideTopInfo.getLayoutParams(); //constraintSet = new ConstraintSet(); //constraintSet.clone(constraintLayout); final ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_front); scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { float percentage = scrollView.getScrollY() * 0.0001f; // 0.001f faster // 0.00001f slower parallax animation Log.d("mLog", String.valueOf(percentage)); if(percentage >= 0) { // my XML percentage value was 12% params.guidePercent = 0.12f - percentage; // up //params.guidePercent = 0.12f + percentage; // downm guideTopInfo.setLayoutParams(params); //constraintSet.setGuidelinePercent(R.id.guideline2, 0.12f - percentage); //TransitionManager.beginDelayedTransition(constraintLayout); //constraintSet.applyTo(constraintLayout); } } }); } 

关于视差的另一个答案 ,如果有人有兴趣的话。 ;)

此代码会将guidePercent更改为0

 ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) guideline.getLayoutParams(); lp.guidePercent = 0; guideline.setLayoutParams(lp); 

您需要使用ConstraintSet对象在代码中设置layout_constraintGuide_percent。

下面是在代码中设置layout_constraintGuide_percent的代码。 首先,您需要创建约束集对象,调用clone方法传递constraintlayout,然后调用setGuidelinePercent传递指南ID和比率。

  ConstraintSet constraintSet = new ConstraintSet(); constraintSet.clone(constraintLayout); constraintSet.setGuidelinePercent(R.id.guideline, 0.4f);