如何将ConstraintLayout添加到LinearLayout中

huangapple go评论41阅读模式
英文:

How to add a ConstraintLayout to a LinearLayout

问题

以下是您要翻译的内容:

"问题:如何将ConstraintLayout添加到LinearLayout中?

我尝试过:

LinearLayout linear = (LinearLayout) findViewById(R.id.idContent);
ConstraintsLayout cst = (ConstraintsLayout) findViewById(R.id.idExample);
linear.addView(cst);

问题:错误:无法将空的子视图添加到ViewGroup中"

英文:

as the title states, i do have two Elements:

  1. LinearLayout:

        <LinearLayout
             android:id="@+id/idContent"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             app:layout_constraintBottom_toBottomOf="parent"
             app:layout_constraintEnd_toEndOf="parent"
             app:layout_constraintHorizontal_bias="0.384"
             app:layout_constraintStart_toStartOf="parent"
             app:layout_constraintTop_toTopOf="parent"
             app:layout_constraintVertical_bias="0.419"
             android:orientation="horizontal">
    
         </LinearLayout>
    
  2. ConstraintsLayout

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res                                               `/android"`
    
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id="@+id/idExample">
    
      <EditText
             android:id="@+id/iddas"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:ems="10"
             android:inputType="date"
            />
     </androidx.constraintlayout.widget.ConstraintLayout>
    

Quesiton: How to add the ConstraintLayout to the LinearLayout?

What i tried:

LinearLayout linear = (LinearLayout) findViewById(R.id.idContent);
ConstraintsLayout cst = (ConstraintsLayout) findViewById(R.id.idExample);
linear.addView(cst);

Issue: Error: Cannot add a null child view to a ViewGroup

答案1

得分: 0

我猜它是 null,因为它从未被填充。假设包含 ConstraintsLayout 的布局是 my_layout.xml,现在你应该首先填充它,然后将它添加到 LinearLayout 中:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View cst = layoutInflater.inflate(R.layout.my_layout, null);
linear.addView(cst);
英文:

I guess it is null because it has never been inflated. Assume the layout that contains the ConstraintsLayout is my_layout.xml, now you should inflate it first, then add it to the LinearLayout:

LayoutInflater layoutInflater = LayoutInflater.from(context);
View cst = layoutInflater.inflate(R.layout.my_layout, null);
linear.addView(cst);

huangapple
  • 本文由 发表于 2020年7月22日 23:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63037602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定