【问题标题】:Android ConstraintLayout ConstraintLayout.LayoutParams.WRAP_CONTENT isn't workingAndroid ConstraintLayout ConstraintLayout.LayoutParams.WRAP_CONTENT 不起作用
【发布时间】:2023-03-25 15:47:02
【问题描述】:

我尝试以编程方式添加 ConstraintLayout。它正在工作,但 WRAP_CONTENT 不工作。布局始终为MATCH_PARENT

Android 开发者页面没有为 ConstraintLayout.LayoutParams 列出 WRAP_CONTENT

我的代码:

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);

【问题讨论】:

    标签: android android-layout layout android-constraintlayout layoutparams


    【解决方案1】:

    您正在将视图 (ConstrainLayout) 添加到 RelativeLayout,因此您应该使用 RelativeLayout 参数。试试这个(同时检查你的导入是否正确):

    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));
        }
    }
    

    结果(红底约束布局为WRAP_CONTENT):

    【讨论】:

    • 谢谢。问题是我不想在 ConstraintLayout 中添加视图(稍后将添加一些内容。)当 ConstraintLayout 中没有任何内容时,它是 MATCH_PARENT(不是真正的 MATCH_PARENT,因为当我保存显示的 xml 代码时,它显示的是 WRAP_CONTENT 但整个 Layout 是红色的...)
    • 哦,是的,我现在看到了。因此,您可以将可见性设置为GONE,然后在添加视图后将其更改为VISIBLE
    猜你喜欢
    • 2018-11-28
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多