我想以编程方式添加CardView。
这是我的主要活动XML布局(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearLayout1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
</LinearLayout>
这是我的CardViewTemplate(card_view_template.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cardViewTemplate"
android:layout_width="160dp"
android:layout_height="190dp"
android:layout_margin="10dp"
android:clickable="true"
android:foreground="?android:selectableItemBackground">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="This is a Card" />
</androidx.cardview.widget.CardView>
这是我的Java代码(Mainactivity.java)
LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
inflater.inflate(R.layout.card_view_template,parent);
一切正常,直到这里。
现在,由于要使用多个CardView,我想在 activity_main.xml 中的特定位置添加Card,我想在特定位置添加Card。因此,我尝试了以下代码,而不是上面的代码:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.card_view_template,null);
ViewGroup parent = findViewById(R.id.linearLayout1);
parent.addView(view,0);