I have two different xml files in an Android project that are very similar -- they both specify an ImageView and a TextView -- the only difference is that they have a different text and image source specified in each one.
frog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/frog">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Frog"
/>
</LinearLayout>
penguin.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/penguin">
</ImageView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Penguin"
/>
</LinearLayout>
How can I refactor these two files into a single reusable component, such that I can use them like this?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<CustomLayout imageSrc="@drawable/penguin" text="Penguin">
<CustomLayout imageSrc="@drawable/frog" text="Frog">
</LinearLayout>
I hate having to copy and paste code everywhere in my app so refactoring here would be great. I've tried using ChatGPT, looking at conversations here on StackOverflow, and looking on the official documentation for Android, but haven't been able to find a simple answer that works. Can anyone help?
Thank you in advance!
custom_animal_view.xml
CustomAnimalView.kt
Usage
You can also use it this way in
ActivityandFragment.Sample Your UseCase
If you want to do it using
attr.attr.xml
CustomAnimalV2View.kt
Usage