Android: GridView trong Android

Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực

GridView trong Android hiển thị các item trong mảng lưới hai chiều có thể scroll và các item này không cần thiết phải được định nghĩa trước, nhưng chúng tự động chèn vào Layout bằng cách sử dụng một ListAdapter

Grid View trong Android
Grid View

Một Adapter thực sự là cầu nối giữa các thành phần UI và nguồn dữ liệu để điền dữ liệu vào trong thành phần UI. Adapter giữ dữ liệu và gửi dữ liệu tới Adapter View, từ đó view có thể lấy dữ liệu từ Adapter View đó và hiển thị dữ liệu trên các view khác nhau ở dạng Spinner, ListView, GridView, …

ListView và GridView là các lớp con của AdapterView và chúng có thể được dùng để nạp cho một Adapter để truy xuất dữ liệu từ một nguồn bên ngoài và tạo một View để hiển thị từng dữ liệu.

Các thuộc tính của GridView trong Android

Bảng dưới liệt kê một số thuộc tính riêng cho GridView:

Thuộc tính Miêu tả
android:id Đây là ID nhận diện GridView
android:columnWidth Xác định độ rộng cố định cho mỗi cột. Có thể là px, dp, sp, in, hoặc mm
android:gravity Xác định gravity bên trong mỗi ô. Giá trị có thể là top, bottom, left, right, center, center_vertical, center_horizontal ...
android:horizontalSpacing Xác định khoảng cách mặc định theo chiều ngang giữa các cột. Có thể là px, dp, sp, in, hoặc mm
android:numColumns Xác định có bao nhiêu cột để hiển thị. Có thể là một giá trị nguyên, như "100" hoặc auto_fit nghĩa là hiển thị bao nhiêu cột để có thể điền vào không gian có sẵn
android:stretchMode Xác định cách các cột nên dãn ra để điền vào không gian còn trống. Nó phải là một trong các giá trị: −
  • none: Vô hiệu hóa việc mở rộng
  • spacingWidth: Khoảng cách giữa mỗi cột được dãn ra
  • columnWidth: Mỗi cột được kéo dãn ra như nhau
  • spacingWidthUniform: Khoảng cách kéo dãn ra là đồng nhất
android:verticalSpacing Định nghĩa khoảng cách mặc định theo chiều dọc giữa các hàng. Có thể là trong px, dp, sp, in, hoặc mm

Ví dụ

Ví dụ sau sẽ minh họa cách làm việc với GridView.

Sau đây là nội dung của file src/v1study.com.gridview/MainActivity.java:

package v1study.com.gridview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends AppCompatActivity {

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

    GridView gridView = findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter(this));
  }
}

Sau đây là nội dung của file res/layout/activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  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">

  <GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="300dp"
    android:columnWidth="90dp"
    android:gravity="center"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.767"/>

  <TextView
    android:text="@string/v1study_s_courses"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    android:layout_marginTop="100dp"
    app:layout_constraintHorizontal_bias="0.434"
    android:textSize="30sp"
    android:textStyle="bold"
    android:textColor="#4CAF50"/>

  <TextView
    android:text="@string/click_show_more"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView2"
    android:textSize="18sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    android:layout_marginTop="16dp"
    app:layout_constraintHorizontal_bias="0.445"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Sau đây là nội dung của res/values/strings.xml:

<resources>
    <string name="app_name">GridViewV1Study</string>
  <string name="v1study_s_courses">V1Study\'s courses</string>
  <string name="click_show_more"><![CDATA[(Click =>Show more)]]></string>
</resources>

Sau đây là nội dung của file src/v1study.com.gridview/ImageAdapter.java:

package v1study.com.gridview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
  private Context context;

  //Hàm to:
  ImageAdapter(Context context) {
    this.context = context;
  }

  @Override
  public int getCount() {
    return mThumbIds.length;
  }

  @Override
  public Object getItem(int i) {
    return null;
  }

  @Override
  public long getItemId(int i) {
    return 0;
  }

  //To ImageView mi cho mi item mà Adapter tham chiếu ti
  @Override
  public View getView(int i, View view, ViewGroup viewGroup) {
    ImageView imageView;
    if (view == null) {
      imageView = new ImageView(context);
      imageView.setLayoutParams(new GridView.LayoutParams(250, 250));
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
      imageView.setPadding(8, 8, 8, 8);
    } else {
      imageView = (ImageView) view;
    }
    imageView.setImageResource(mThumbIds[i]);

    return imageView;
  }

  public Integer[] mThumbIds = {
    R.drawable.v1study_logo, R.drawable.v1study_android,
    R.drawable.v1study_java, R.drawable.v1study_php_laravel,
    R.drawable.v1study_python, R.drawable.v1study_lego_wedo_20,
    R.drawable.v1study_react, R.drawable.v1study_sql_server
  };
}

Chạy ứng dụng:

GridView Layout trong Android

Ví dụ về SubActivity trong Android

Từ ví dụ trên ta sẽ kế thừa các tính năng để thực hiện việc hiển thị grid image đã lựa chọn trong toàn màn hình. Để làm được điều này, ta cần tạo một Activity mới, khai báo nó trong file AndroidManifest.xml, định nghĩa Layout liên quan và cuối cùng kết nối sub-activity đó với MainActivity. Sau đây là các bước để update ví dụ trên:

Bước Miêu tả
1 Tạo một lớp Activity mới có tên SingleViewActivity.java nằm trong package là v1study.com.gridview
2 Tạo một file layout cho Activity mới này, file này có tên single_view.xml và nằm trong thư mục res/layout/
3 Khai báo Activity mới trong AndroidManifest.xml bằng cách sử dụng thẻ <activity.../> (V1Study xin nhấn mạnh là một ứng dụng có thể có một hoặc nhiều Activity)
4 Chạy ứng dụng để kiểm tra kết quả.

Sau đây là nội dung của file res/layout/single_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
      android:id="@+id/imageViewSingleView"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"/>

  </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Sau đây là nội dung của new activity file src/v1study.com.gridview/SingleViewActivity.java:

package v1study.com.gridview;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class SingleViewActivity extends AppCompatActivity {
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_view);

    //Ly d liu intent
    Intent intent=getIntent();

    //Ly id nh đã chn
    int position= intent.getExtras().getInt("id");
    ImageAdapter imageAdapter=new ImageAdapter(this);

    ImageView imageView=findViewById(R.id.imageViewSingleView);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);
  }
}

Sau đây là nội dung của file MainActivity.java đã được sửa đổi:

package v1study.com.gridview;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends AppCompatActivity {

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

    GridView gridView = findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter(this));

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //Gi intent ti SingleViewActivity
        Intent intent=new Intent(getApplicationContext(),SingleViewActivity.class);

        //Truyn ch s (index) ca nh
        intent.putExtra("id",position);
        startActivity(intent);
      }
    });
  }
}

Sau đây là nội dung của AndroidManifest.xml trong đó khai báo thêm activity SingleViewActivity:

<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:dist="http://schemas.android.com/apk/distribution"
  package="v1study.com.gridview">

  <dist:module dist:instant="true"/>

  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>

        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>

    <activity android:name=".SingleViewActivity"/>
  </application>

</manifest>

Chạy lại ứng dụng:

GridView Layout trong Android

Bây giờ nếu bạn click chuột vào một trong các hình ảnh (ảnh Android chẳng hạn) thì nó sẽ chỉ hiển thị một hình ảnh đó như dưới đây:

Android Single GridView Layout

» Tiếp: TextView trong Android
« Trước: ListView trong Android
Các khóa học qua video:
Python SQL Server PHP C# Lập trình C Java HTML5-CSS3-JavaScript
Học trên YouTube <76K/tháng. Đăng ký Hội viên
Viết nhanh hơn - Học tốt hơn
Giải phóng thời gian, khai phóng năng lực
Copied !!!