3

I try to add a ConstraintLayout programmatically. It's working but WRAP_CONTENT isn't working. The Layout is always MATCH_PARENT.

The Android Developer page doesn't list WRAP_CONTENT for ConstraintLayout.LayoutParams

My Code:

RelativeLayout rl_main = findViewById(R.id.rl_main);
ConstraintLayout cl = new ConstraintLayout(this);
cl.setId(0);
ConstraintLayout.LayoutParams clp = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT_WRAP);
cl.setLayoutParams(clp);
cl.setBackgroundColor(Color.parseColor("#000000"));
rl_main.addView(cl);
iknow
  • 8,358
  • 12
  • 41
  • 68
Marvin Stelter
  • 289
  • 4
  • 14

1 Answers1

0

You are adding a view (ConstrainLayout) to RelativeLayout so You should use RelativeLayout params. Try this (also check if Your import is correct):

import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout rl_main = findViewById(R.id.rl_main);
        ConstraintLayout cl = new ConstraintLayout(this);
        cl.setId(0);
        RelativeLayout.LayoutParams clp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

        cl.setLayoutParams(clp);
        cl.setBackgroundColor(Color.parseColor("#FF0000"));
        rl_main.addView(cl);

        //test adding button
        cl.addView(new Button(this));
    }
}

Result (constraint layout with red background is WRAP_CONTENT):

enter image description here

iknow
  • 8,358
  • 12
  • 41
  • 68
  • Thank You. The problem is that I don't want to add a View inside the ConstraintLayout (Something will be added later.) When theres nothing inside the ConstraintLayout it's MATCH_PARENT (Not really MATCH_PARENT, because when I save the displayed xml code it's showing WRAP_CONTENT but the entire Layout is red...) – Marvin Stelter Aug 10 '20 at 18:57
  • Oh, yeah I see it now. So You can just set visibility to `GONE` and after You add View change it to `VISIBLE`. – iknow Aug 10 '20 at 19:04