Skip to content

Changing LayoutParams with an OnClickListener?

I’m learning how to work with LayoutParams. there is something I don’t understand about setting layout params. here is my code:

 layout = findViewById(R.id.relative_layout);
    img = findViewById(R.id.img_view);
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) img.getLayoutParams();

    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            params.addRule(RelativeLayout.CENTER_IN_PARENT);

            img.setLayoutParams(params); //Setting LayoutParams?

        }
    });

If I put this code directly in OnCreate() method, it works fine but why when I transfer it inside an OnClickListener, I need to set the layout params again? what logic is behind this?

Answer

You are modifying the Params after they are being set. This means that the current solution for solving the constraints optimally is not valid anymore, and they need to be recalculated. By changing this one constraint, your whole layout may change.

By setting the layout params on the layout again, it’s resolving and recalculating new positions for every view, including your newly added constraint. As long as you don’t call recalculation methods, the old layout will be used.