Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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);
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
):
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.