I want to add CardView programmatically.
Here is my Main Activity XML Layout (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>
Here is my 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>
Here is my Java Code (MainActivity.java)
LayoutInflater inflater = getLayoutInflater();
ViewGroup parent = findViewById(R.id.linearLayout1);
inflater.inflate(R.layout.card_view_template, parent);
Everything works fine till here.
Now I want to add Card at certain position in my activity_main.xml as I am using multiple CardViews, I want to add Cards at certain position. Hence, instead of the above code, I tried this:
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.card_view_template, null);
ViewGroup parent = findViewById(R.id.linearLayout1);
parent.addView(view, 0);
But it does not inflate properly. Only the Text is visible, The Card does not seem to appear.