0

1つのConstraint Layoutに動的に作成されたImageViewがあります。アプリケーションを実行すると、ImageViewの位置が定義されていないため、ImageViewが左上隅に表示されます。 イメージビューの位置を動的に設定するにはどうしたらいいですか?Constraint LayoutでImageViewの位置を動的に設定するには

Iは、任意の提案が高く評価されているコード

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout); 

ImageView imageView = new ImageView(ChooseOptionsActivity.this); 
imageView.setImageResource(R.drawable.redlight); 

layout.addView(imageView); 

setContentView(layout); 

下に書かれています。

答えて

1

ImageViewに適用されるConstraintSetを使用する必要があります。 ConstraintSetのドキュメントはhereです。

このクラスを使用すると、ConstraintLayoutで使用する一連の制約をプログラムで定義できます。これにより、制約を作成して保存し、既存のConstraintLayoutに適用することができます。 ConstraintsSetはさまざまな方法で作成できます。

ここで最も難しいのは、ビューが中央に配置されている方法です。センタリング手法の詳細な説明はhereです。ご例えば

、次のコードは十分でしょう。

// Get existing constraints into a ConstraintSet 
    ConstraintSet constraints = new ConstraintSet(); 
    constraints.clone(layout); 
    // Define our ImageView and add it to layout 
    ImageView imageView = new ImageView(this); 
    imageView.setId(View.generateViewId()); 
    imageView.setImageResource(R.drawable.redlight); 
    layout.addView(imageView); 
    // Now constrain the ImageView so it is centered on the screen. 
    // There is also a "center" method that can be used here. 
    constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT); 
    constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT); 
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 
      0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f); 
    constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP, 
      0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f); 
    constraints.applyTo(layout); 
関連する問題