簡體   English   中英

如何動態地將線性布局(作為子項)添加到約束布局(父級)?

[英]How to dynamically add a linear layout (as a child) to a constraint layout (parent)?

我定義了一種方法來創建線性布局並將其添加到父布局。 但它沒有用。 我想我犯了錯​​誤。

    public void methodName() {
        LinearLayout linearLayout = new LinearLayout(MainActivity.this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setBackgroundColor(Color.RED);
        ConstraintLayout main = (ConstraintLayout) findViewById(R.id.mainLayout);
        main.addView(linearLayout);
   }

要向ConstraintLayout添加視圖,必須使用ConstraintSet添加約束。

在為約束布局添加動態視圖時,它與其他布局略有不同。 您需要指定約束,如下所示: -

     ConstraintLayout main = (ConstraintLayout) findViewById(R.id.mainLayout);
     ConstraintSet set = new ConstraintSet();

     LinearLayout linearLayout = new LinearLayout(MainActivity.this);
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
     linearLayout.setLayoutParams(params);
     linearLayout.setOrientation(LinearLayout.HORIZONTAL);
     linearLayout.setBackgroundColor(Color.RED);
     main.addView(linearLayout,0);
     set.clone(main);
     set.connect(linearLayout.getId(), ConstraintSet.TOP, main.getId(), ConstraintSet.TOP, 60);
     set.applyTo(main);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM