0

我在一個約束佈局中有一個動態創建的ImageView。一旦我運行應用程序,ImageView將顯示在左上角,因爲沒有爲ImageView定義位置。 如何動態設置ImageView的位置(比方說CENTER)。如何在約束佈局中動態設置ImageView的位置

我已經寫下面代碼

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

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

layout.addView(imageView); 

setContentView(layout); 

任何建議是高度讚賞。

回答

1

您將需要使用應用於ImageViewConstraintSet來居中。 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);