Daniele Daniele - 5 months ago 10
Android Question

Implement a custom ListView in Android

I've created a listView in my MainActivity and another layout file for the row layout which looks like this:

my row_layout

The problem is, how do I implement it? Where do I set all the Strings that have to go in text? Where the ones that go in note?

I've looked on the internet but I could find someone who had a similar listView as mine.

I know that for Strings I can use arrays, but can I set up an array of ImageViews too?

I'd really appreciate if you could provide me with a detailed answer in which you explain me how to "put things" inside my listView

EDIT: added row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content">

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text"
android:textAllCaps="true"
android:textSize="36sp"
android:layout_marginTop="10dp"
android:fontFamily="sans-serif-condensed"
android:textStyle="bold"
android:textColor="@color/black" />

<TextView
android:id="@+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/text"
android:text="note note note"
android:layout_marginTop="2dp"
android:fontFamily="sans_serif_medium"
android:textSize="24sp"/>

<ImageView
android:layout_width="200dp"
android:layout_height="140dp"
android:scaleType="fitCenter"
android:layout_alignParentEnd="true"/>

</RelativeLayout>

Answer

You should create

  1. a class, (lets name it DataModel.java, you can give any name of your wish ) representing your data : String text, note, image url; along with getter and setter methods.
  2. a class extending ArrayAdapter. Override the getView() method. Pass the ArrayList< DataModel > to the custom array adapter created. Create a constructor and call super to call the constructor of ArrayAdapter ": ArrayAdapter(Context context, int resource, List<T> objects).

In the getView method inflate the row layout and set the data [ match the index from the Arraylist with the position parameter of the getView method ]

In the context of your question, I recommend you to study more about view holder pattern and RecyclerView, which will help you understand how things work and how they should be done efficiently.

Comments