我必须创建一个案例,其中我需要插入5个类似卡片的结构,在我的线性布局中activity_main. xml
activity_main布局是这样的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
</LinearLayout>
And the cardview layout is like this :
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/card"
android:layout_height="100dp"
android:layout_width="250dp"
android:background="@color/white"
app:cardCornerRadius="40dp"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:text="Title from Android"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="monospace"/>
<TextView
android:id="@+id/desc"
android:layout_marginTop="40dp"
android:textAlignment="center"
android:text="adding layout dynamically"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="serif"/>
</androidx.cardview.widget.CardView>
在main active onCreate()方法上,我有:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout parent=(LinearLayout) findViewById(R.id.viewMain);
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.text_main,parent,true);
for(int i=0;i<3;i++){
parent.addView(view,i);
}
}
显示的错误如下:
有人能帮我解决这个问题吗,这样我就可以在我的线性布局中动态插入5个类似卡片的结构
改变
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.text_main,parent,true);
到
View view = LayoutInflater.from(this).inflate(R.layout.text_main, null);
并在for循环中添加LayoutInflater
代码
在MainActivity.java
中添加以下代码
LinearLayout parent=(LinearLayout) findViewById(R.id.viewMain);
for (int i = 0; i < 3; i++) {
View view = LayoutInflater.from(this).inflate(R.layout.text_main, null);
TextView title = view.findViewById(R.id.title);
TextView desc = view.findViewById(R.id.desc);
parent.addView(view);
}