如何以编程方式设计线性布局

how to design Linear layout programmatically

如何以编程方式执行此类操作? MaterialCardView.I 中必须有一个 Checkbox 和两个垂直 textview 尝试使用 Linearlayout 但我无法解决它。

 LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT

    );
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    mCardView=new MaterialCardView(this);
    mCardView.setLayoutParams(layoutparams);
    mCardView.setElevation(2);
    linearLayout.addView(mCardView);

    LinearLayout linearLayout1=new LinearLayout(this);
    linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
    linearLayout1.setLayoutParams(layoutparams);
    linearLayout.addView(linearLayout1)

    checkBox=new CheckBox(this);
    linearLayout1.addView(checkBox);
    txt_baslik=new TextView(this);
    txt_tarih=new TextView(this);
    txt_baslik.setLayoutParams(layoutparams);
    txt_tarih.setLayoutParams(layoutparams);
    txt_baslik.setText("deneme baslik");
    txt_tarih.setText("deneme tarih");
    linearLayout1.addView(txt_baslik);
    linearLayout1.addView(txt_baslik);

    LinearLayout linearLayout2=new LinearLayout(this);
    linearLayout2.setOrientation(LinearLayout.VERTICAL);
    linearLayout2.setLayoutParams(layoutparams);
    linearLayout.addView(linearLayout2);

我很困惑

你可以这样做:

LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);

LinearLayout linearLayout=new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);

CardView mCardView=new MaterialCardView(this);
mCardView.setLayoutParams(layoutparams);
mCardView.setElevation(2);

CheckBox checkBox=new CheckBox(this);
LinearLayout.LayoutParams checkBoxParam = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);
checkBoxParam.gravity = Gravity.CENTER;
checkBox.setLayoutParams(checkBoxParam);

LinearLayout verticalLinLayout=new LinearLayout(this);
verticalLinLayout.setOrientation(LinearLayout.VERTICAL);
verticalLinLayout.setLayoutParams(layoutparams);

TextView txt_baslik=new TextView(this);
TextView txt_tarih=new TextView(this);

txt_baslik.setLayoutParams(layoutparams);
txt_tarih.setLayoutParams(layoutparams);

txt_baslik.setText("deneme baslik");
txt_tarih.setText("deneme tarih");

verticalLinLayout.removeAllViews();
verticalLinLayout.addView(txt_baslik);
verticalLinLayout.addView(txt_tarih);
linearLayout.addView(checkBox);
linearLayout.addView(verticalLinLayout);
mCardView.addView(linearLayout);

最后不要忘记将 mCardView 添加到您的父视图中。