Android - Resize UI widget created dynamically

215 Views Asked by At

I try to create a button dynamically with in Java and add it some constraints to position it in the center of my constrainLayout. So I write this code:

import android.app.Activity;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.widget.Button;

public class SelectGameActivity extends Activity {

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

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

    Button button = new Button(this);
    button.setText("test");
    button.setId(213);
    constraintLayout.addView(button);

    constraintSet.connect(button.getId(), ConstraintSet.LEFT, R.id.constraintLayout, ConstraintSet.LEFT);
    constraintSet.connect(button.getId(), ConstraintSet.RIGHT, R.id.constraintLayout, ConstraintSet.RIGHT);
    constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.constraintLayout, ConstraintSet.TOP);
    constraintSet.connect(button.getId(), ConstraintSet.BOTTOM, R.id.constraintLayout, ConstraintSet.BOTTOM);
    constraintSet.applyTo(constraintLayout);
    }
}

It works but the button fills all the screen:

enter image description here

I think it is because my button doesn't have any specific height and width. I tried several codes to give it a size but no effect. Could someone give me some hints to resize my button correctly ?

Thank you very much !

Charles

1

There are 1 best solutions below

1
On BEST ANSWER

Try setting the button's dimensions to WRAP_CONTENT like this:

    constraintSet.constrainHeight(button.getId(), ConstraintSet.WRAP_CONTENT);
    constraintSet.constrainWidth(button.getId(), ConstraintSet.WRAP_CONTENT);