Tuesday, March 31, 2020

Android custom listview example

INTRODUCE  ANDROID CUSTOM LISTVIEW EXAMPLE

In this lesson, you'll learn how to customize the layout for ListView in your Android application. I think this exercise is very important and practical because in Android apps related to ListView, most of us have to customize it to meet customer requirements.
Each line in the ListView will have objects: TextView and ImageView.

Create the XML interface

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lvBookList"
        android:layout_weight="1" />
</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
    android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:textColor="@color/title"
        android:textSize="16dp"
        android:textStyle="bold"
        android:layout_alignParentTop="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/author"
        android:layout_below="@id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/price"
        android:textColor="@color/year"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/price"
        android:layout_alignEnd="@+id/price"
        android:layout_below="@+id/author">

        <ImageView
            android:layout_width="90px"
            android:layout_height="90px"
            app:srcCompat="@drawable/like"
            android:id="@+id/btnLike"
            android:layout_weight="1" />
    </LinearLayout>

</RelativeLayout> 
Java code part
Create Book model to save data
public class Book {
    private String title;
    private String  author;
    private String  price;

    public Book() {
    }

    public Book(String title, String author, String price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", price='" + price + '\'' +
                '}';
    }
}
 Create custom adapter: BookAdapter.java
public class BookAdapter extends ArrayAdapter<Book> {

    Activity context;
    int resource;   
    List<Book> objects;
    /**
     * @param context
     * @param resource
     * @param objects
     * */
    public BookAdapter(Activity context, int resource, List<Book> objects) {
        super(context, resource, objects);
        this.context=context;
        this.resource=resource;
        this.objects=objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater= this.context.getLayoutInflater();
        View row = inflater.inflate(this.resource,null);

        TextView txtTitle = (TextView) row.findViewById(R.id.title);
        TextView txtAuthor = (TextView) row.findViewById(R.id.author);
        TextView txtPrice = (TextView) row.findViewById(R.id.price);
        ImageView btnLike = (ImageView) row.findViewById(R.id.btnLike);
        /** Set data to row*/
        final Book book = this.objects.get(position);
        txtTitle.setText(book.getTitle());
        txtAuthor.setText(book.getAuthor());
        txtPrice.setText(book.getPrice());

        /**Set Event Onclick*/
        btnLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMessage(book);
            }
        });
        return row;
    }
    /** Show mesage*/
    private void showMessage(Book book) {
        Toast.makeText(this.context,book.toString(),Toast.LENGTH_LONG).show();
    }
}
At MainAcitivity.java
public class MainActivity extends AppCompatActivity {
    ListView lvDanhBa;
    ArrayList<Book> bookList;
    BookAdapter bookAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addControls();
        addEvent();
    }

    private void addControls() {

        lvDanhBa = (ListView) findViewById(R.id.lvBookList);
        bookList = new ArrayList<>();
        /**
         * @param MainActivity.this
         * @param R.layout.item
         * @param bookList
         * */
        bookAdapter = new BookAdapter(MainActivity.this,R.layout.item,bookList);
        lvDanhBa.setAdapter(bookAdapter);
    }

    private void addEvent() {
        createData();
    }

    /** Add data to bookList*/
    public void createData() {
        Book book = new Book("Kỳ Án Ánh Trăng","Xác treo trong nhà gỗ","100.000");
        bookList.add(book);
        book = new Book("Tuyết Đoạt Hồn","Qủy Cổ Nữ","100.000");
        bookList.add(book);
        book = new Book("Tơ Đòng Rỏ Máu","Xác treo trong nhà gỗ","100.000");
        bookList.add(book);
        book = new Book("Hồ Tuyệt Mệnh","Qủy Cổ Nữ","100.000");
        bookList.add(book);
        book = new Book("Nỗi Đau Của Đom Đóm","Qủy Cổ Nữ","100.000");
        bookList.add(book);
        bookAdapter.notifyDataSetChanged();
    }
}
OUTPUT:
Android custom listview example

No comments:

Post a Comment