-1

ConstraintLayoutに含まれるすべてのビューをJavaコードで簡単に中心に配置するにはどうすればよいですか?ConstraintLayout内のすべてのビューを中央に配置

FrameLayoutを使用すると、中心重力を適用するだけで済みます。

私はGUIビルダーを使用できません。レイアウトは実行時に生成する必要があります。ここで

+0

可能な複製(https://stackoverflow.com/questions/39296627/android-constraint-layout -programmatically) – 0X0nosugar

答えて

0

私が働いてレイアウトされて:すべてのビューを中央に

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
} 

enter image description here

、:

<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/parent" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <View 
     android:id="@+id/first" 
     android:layout_width="200dp" 
     android:layout_height="200dp" 
     android:background="#f00"/> 

    <View 
     android:id="@+id/second" 
     android:layout_width="150dp" 
     android:layout_height="150dp" 
     android:background="#0f0"/> 

    <View 
     android:id="@+id/third" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:background="#00f"/> 

</android.support.constraint.ConstraintLayout> 

はここだけでこのレイアウトを表示する完全にダムの活動ですConstraintSetを作成し、clone()を使用して初期化してから、すべての子をループし、水平および垂直に中央に配置します。

ConstraintLayout parent = (ConstraintLayout) findViewById(R.id.parent); 
    ConstraintSet constraintSet = new ConstraintSet(); 
    constraintSet.clone(parent); 

    for (int i = 0; i < parent.getChildCount(); ++i) { 
     View child = parent.getChildAt(i); 

     constraintSet.centerHorizontally(child.getId(), parent.getId()); 
     constraintSet.centerVertically(child.getId(), parent.getId()); 
    } 

    parent.setConstraintSet(constraintSet); 

そして今、それは次のようになります。[?Androidの制約レイアウトプログラム]の

enter image description here

関連する問題