[Khóa học lập trình Android] Bài 08 Hiển thị dữ liệu lên ứng dụng Android

Đây là khóa học lập trình Android miễn phí với nội dung các bài học mạch lạc và dễ hiểu với những bài hướng dẫn lập trình ứng dụng Android cơ bản nhất. Nội dung phần hướng dẫn này trình bày hiển thị dữ liệu lên ứng dụng Android.

Để hiển thị dữ liệu lên ứng dụng Android mình sẽ sử dụng RecyclerView, RecyclerView trong Android giúp hiển thị dữ liệu dưới dạng danh sách theo chiều ngang hoặc chiều dọc.

[Khóa học lập trình Android] Bài 08 Hiển thị dữ liệu lên ứng dụng Android

Trong đó:

  • Lớp RecyclerView.Adapter: được dùng để xử lý hoặc hiển thị dữ liệu lên các Item trong RecyclerView.
  • Lớp RecyclerView.ViewHolder: được dùng để có thể tái sử dụng View nhằm tránh việc khởi tạo View mới nhằm cải thiện hiệu suất ứng dụng.
  • Lớp RecyclerView.LayoutManager: được dùng để cung cấp một số kiểu trình bày bao gồm hiển thị dữ liệu bao gồm LinearLayoutManager (giúp hiển thị dữ liệu dạng danh sách cuộn thẳng đứng hoặc nằm ngang), GridLayoutManager (giúp hiển thị dữ liệu dạng lưới) và StaggeredGridLayoutManager (giúp hiển thị dữ liệu dạng so le).
  • Lớp RecyclerView.ItemAnimator: được dùng để chuyển đổi màu sắc, vị trí, hướng của một đối tượng trên màn hình theo thời gian.
  • Lớp RecyclerView.ItemDecoration: được dùng để thiết lập nhiều hiệu ứng giữa các danh mục.

Bạn mở tập tin content_currency.xml và thêm RecyclerView vào như sau:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".view.CurrencyActivity"
    tools:showIn="@layout/activity_currency">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:background="#FFFFFF"
        android:orientation="horizontal">

        <TextView
            android:layout_width="110dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:gravity="center_vertical"
            android:text="Ngoại tệ"
            android:textStyle="bold" />

        <TextView
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:gravity="right|center"
            android:text="Mua TM"
            android:textStyle="bold" />

        <TextView
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:gravity="right|center"
            android:text="Mua CK"
            android:textStyle="bold" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginRight="5dp"
            android:gravity="right|center"
            android:text="Bán ra"
            android:textStyle="bold" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvCurrency"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Thiết kế layout trình bày cách hiển thị dữ liệu cho mỗi mục, như trong ví dụ này mình sẽ thiết kế layout hiển thị lần lượt từ trái qua phải bao gồm thị trường, giá mua tiền mặt, giá mua chuyển khoản và giá bán ra. Bạn tạo tập tin XML đặt tên item_currency.xml như sau:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="110dp"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvSerial"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:gravity="center_vertical"
            android:textStyle="bold"
            android:text="USD" />

        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:textSize="10dp"
            android:text="US DOLLAR" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvBuy"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:gravity="right|center"
            android:text="22,750.00" />

        <TextView
            android:id="@+id/tvTransfer"
            android:layout_width="80dp"
            android:layout_height="match_parent"
            android:gravity="right|center"
            android:text="22,750.00" />

        <TextView
            android:id="@+id/tvSell"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="right|center"
            android:text="22,820.00" />

    </LinearLayout>

</LinearLayout>

Tạo lớp CurrencyAdapter.java nằm trong package adapter và kế thừa RecyclerView.Adapter

package com.teamvietdev.tctt.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.teamvietdev.tctt.R;
import com.teamvietdev.tctt.model.Currency;

import java.util.List;

public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.VHolder> {

    private List<Currency> listCurrency = null;
    private Currency currency = null;

    public CurrencyAdapter(List<Currency> listCurrency) {
        this.listCurrency = listCurrency;
    }

    @Override
    public CurrencyAdapter.VHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_currency, parent, false);
        return new CurrencyAdapter.VHolder(view);
    }

    @Override
    public void onBindViewHolder(CurrencyAdapter.VHolder holder, final int position) {
        currency = listCurrency.get(position);
        holder.tvSerial.setText(currency.getSerial());
        holder.tvName.setText(currency.getName());
        holder.tvBuy.setText(currency.getBuy());
        holder.tvTransfer.setText(currency.getTransfer());
        holder.tvSell.setText(currency.getSell());
    }

    @Override
    public int getItemCount() {
        if (listCurrency != null && !listCurrency.isEmpty()) {
            return listCurrency.size();
        }
        return 0;
    }

    public static class VHolder extends RecyclerView.ViewHolder {

        private TextView tvSerial;
        private TextView tvName;
        private TextView tvBuy;
        private TextView tvTransfer;
        private TextView tvSell;

        public VHolder(View view) {
            super(view);
            tvSerial = (TextView) view.findViewById(R.id.tvSerial);
            tvName = (TextView) view.findViewById(R.id.tvName);
            tvBuy = (TextView) view.findViewById(R.id.tvBuy);
            tvTransfer = (TextView) view.findViewById(R.id.tvTransfer);
            tvSell = (TextView) view.findViewById(R.id.tvSell);
        }

    }

}

Trong đó:

  • Phương thức onCreateViewHolder(ViewGroup parent, int viewType) được sử dụng để tạo ra một RecyclerView.ViewHolder mới và khởi tạo một số trường được sử dụng trong RecyclerView.
  • Phương thức onBindViewHolder(PersonHolder holder, int position) được sử dụng để cập nhật nội dung RecyclerView.ViewHolder tương ứng mỗi vị trí trong danh sách.
  • Phương thức getItemCount() trả về tổng số lượng phần tử.

Bạn mở lớp CurrencyActivity.java và thực hiện gán Adapter cho RecyclerView

package com.teamvietdev.tctt.view;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;

import com.teamvietdev.tctt.R;
import com.teamvietdev.tctt.adapter.CurrencyAdapter;
import com.teamvietdev.tctt.helper.MyViewInterface;
import com.teamvietdev.tctt.model.Currency;
import com.teamvietdev.tctt.presenter.DataPresenter;
import com.teamvietdev.tctt.presenter.DataPresenterImpl;

import java.util.List;

public class CurrencyActivity extends AppCompatActivity implements MyViewInterface {

    private DataPresenter dataPresenter = null;

    private RecyclerView rvItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_currency);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        rvItem = (RecyclerView) findViewById(R.id.rvCurrency);

        dataPresenter = new DataPresenterImpl(this);
        dataPresenter.getListCurrency("teamvietdev.com");

    }

    @Override
    public void onComplete(String kind, Object obj) {
        Log.d("onComplete", obj.toString());
        List<Currency> listCurrency = (List<Currency>) obj;
        rvItem.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        rvItem.setAdapter(new CurrencyAdapter(listCurrency));
    }

    @Override
    public void onFailed(String msg) {
        Log.d("onFailed", msg);
    }

}

Sau cùng bạn hãy khởi chạy ứng dụng, và xem kết quả có hiển thị được dữ liệu hay không?

Xem nội dung chi tiết hướng dẫn trên Youtube:

Lời kết: Như vậy khóa học lập trình Android miễn phí được chia sẻ bởi Team Việt Dev hy vọng giúp bạn có thêm nhiều kiến thức cơ bản để tự xây dựng cho riêng mình một ứng dụng Android.

(Tác giả: Team Việt Dev)

Bình luận