Tìm hiểu GridView trong Android

Sau đây mình sẽ hướng các bạn làm 1 demo đơn giản, sử dụng hiển thị bảng chữ cái như hình dưới. Khi chúng ta click vào 1 chữ cái nó sẽ hiển thị chữ cái đó lên màn hình.

Ở những bài trước mình đã giới thiệu cho các bạn biết về ListView, hôm nay mình sẽ giới thiệu 1 control khá giống ListView đó là GridView trong lập trình .

1. Giới thiệu về

  • Trong android, GridView cho phép chúng ta sắp xếp các thành phần trong một lưới gồm nhiều dòng và nhiều cột
  • ListView và GridView là lớp con của AdapterView và cả hai đều sử dụng Adapter để nhận dữ liệu, sau đó hiển thị dữ liệu từ Adapter này.
  • Điểm khác nhau là GridView có thiết lập số cột. Dữ liệu luôn đưa vào dưới dạng hình ống (mảng, list một chiều), nhưng dựa vào số cột ta thiết lập mà nó tự động ngắt hàng.

Xem thêm: Bộ tài liệu học  full

2. Hướng dẫn tạo 1 GridView đơn giản

Sau đây mình sẽ hướng các bạn làm 1 demo đơn giản, sử dụng gridview hiển thị bảng chữ cái như hình dưới. Khi chúng ta click vào 1 chữ cái nó sẽ hiển thị chữ cái đó lên màn hình.

B1. Tạo project mới có tên là GridViewDemo

B2. file xml của giao diện chính như sau.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:orientation=”vertical”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    tools:context=”.MainActivity”>
    <TextView
        android:textColor=”#ff2796ff”
        android:layout_marginTop=”20sp”
        android:layout_gravity=”center”
        android:textSize=”25sp”
        android:text=”Demo GridView”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content” />
    <GridView
        android:id=”@+id/grAnphabet”
        android:layout_marginTop=”20dp”
        android:layout_width=”fill_parent”
        android:layout_height=”fill_parent”
        android:numColumns=”5″
        android:layout_gravity=”center”
        android:stretchMode=”columnWidth”>
    </GridView>
</LinearLayout>

các bạn có thể quan sát 1 số thuộc tính của gridview, cũng tương tự listview, gridview có thêm 1 số thuộc tính như

  • numberColoums: số cột được xác định để hiển thị
  • stretchMode: xác định cách thức các cột co giãn để lấp đầy không gian trống có sẵn, sử dụng một trong các giá trị sau:none: Không co giãnspacingWidth: Khoảng cách giữa các cột được co giãncolumnWidth: Mỗi cột được co giãn bằng nhau
  • horizontalSpacing/ verticalSpacing: Xác định khoảng cách giữa các dòng và các cột

B3. Code trong file java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package devpro.com.gridviewdemo;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
    GridView grAnphabet;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        grAnphabet = (GridView) findViewById(R.id.grAnphabet);
        final String[] lstData = new String[]{
                “A”, “B”, “C”, “D”, “E”,
                “F”, “G”, “H”, “I”, “J”,
                “K”, “L”, “M”, “N”, “O”,
                “P”, “Q”, “R”, “S”, “T”,
                “U”, “V”, “W”, “X”, “Y”,
                “Z”
        };
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lstData);
        grAnphabet.setAdapter(adapter);
        //Sự kiện click vào mỗi item trong gridview
        grAnphabet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), lstData[i], Toast.LENGTH_SHORT).show();
            }
        });
    }
}

nếu các bạn đã làm qua listview thì có thể thấy nó rất giống với cách làm của listview. Cũng sử dụng ArrayAdapter để nhận dữ liệu sau đó hiển thị adapter đó. Sau đó run project và các bạn sẽ có kết quả như hình trên.

3. Xây dựng Demo xử dụng GridView phức tạp hơn.

Tiếp tục mình sẽ hướng dẫn các bạn làm 1 demo phức tạp hơn, dùng gridview hiện thị danh sách các ảnh, khi click vào 1 ảnh bất kỳ, ảnh đó sẽ được hiển thị ở 1 màn hình mới. xem hình dưới.

B1. Tạo project mới có tên là GridViewAdvance với cấu trúc như sau.

quan sát project ta sẽ thấy project có 2 layout. Layout main để hiển thị danh sách các ảnh, 1 layout để hiển thị chi tiết ảnh khi được click vào. Phần class cũng có 2 class, 1 class main, và 1 class là Adapter để đưa dữ liệu vào trong gridview. Các bạn cũng thấy thư mục drawable chứa các ảnh mà các bạn muốn hiển thị. các bạn hãy thêm những ảnh của các bạn vào thư mục này.

B2. Các bạn thiết kế các màn hình và màn hình show lên ảnh khi nhấn vào từng ảnh trên màn hình chính.

Chúng ta tạo ra 2 Activity là MainActivity có giao diện màn hình là activity_main.xml và ShowImage có giao diện là show_item_gridview.xml

Màn hình chính:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:orientation=”vertical”
    android:layout_height=”match_parent”
    tools:context=”.MainActivity”>
    <TextView
        android:paddingTop=”25dp”
        android:textColor=”#2796ff”
        android:textSize=”25sp”
        android:layout_gravity=”center”
        android:text=”Demo GridView Advance”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content” />
    <GridView
        android:id=”@+id/grAlbumImage”
        android:layout_width=”fill_parent”
        android:layout_height=”fill_parent”
        android:numColumns=”auto_fit”
        android:horizontalSpacing=”10dp”
        android:verticalSpacing=”10dp”
        android:gravity=”center”
        android:background=”#ffffa06c”
        android:layout_marginTop=”20sp”></GridView>
</LinearLayout>

show_item_gridview.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:orientation=”vertical”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”>
    <TextView
        android:id=”@+id/txtNameImg”
        android:layout_marginTop=”25dp”
        android:text=”ảnh 1″
        android:textColor=”#2796ff”
        android:textSize=”25sp”
        android:gravity=”center”
        android:layout_width=”fill_parent”
        android:layout_height=”50dp” />
    <ImageView
        android:id=”@+id/imgContent”
        android:background=”#ffbc4e”
        android:layout_width=”fill_parent”
        android:layout_height=”0dp”
        android:layout_weight=”9″/>
    <Button
        android:id=”@+id/btnBack”
        android:text=”Back”
        android:layout_gravity=”center”
        android:layout_width=”100dp”
        android:layout_height=”50dp” />
</LinearLayout>

B3. Cấu hình code trong các class.

class MyImageAdapter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Created by Dong on 5/24/2016.
*/
public class MyImageAdapter extends BaseAdapter {
    private Context Context;
    private Integer [] lstIdImg;
    public MyImageAdapter(Context c){
        Context =c;
    }
    public MyImageAdapter(Context c,Integer []arrIds){
        Context =c;
        lstIdImg =arrIds;
    }
    @Override
    public int getCount() {
        return lstIdImg.length;
    }
    @Override
    public Object getItem(int i) {
        return null;
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ImageView imgView;
        if(view==null){
            imgView=new ImageView(Context);
            //can chỉnh lại hình cho đẹp
            imgView.setLayoutParams(new GridView.LayoutParams(300, 300));
            imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imgView.setPadding(8, 8, 8, 8);
        }else{
            imgView=(ImageView) view;
        }
        //lấy đúng vị trí hình ảnh được chọn
        //gán lại ImageResource
        imgView.setImageResource(lstIdImg[i]);
        return imgView;
    }
}

class MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    GridView grAlbum;
    //mảng lưu danh sách các id hình ảnh có sẵn
    Integer[] lstIDImg;
    int[] intArray;
    //Adapter cho GridView
    MyImageAdapter adapter = null;
    ImageView imgContent;
    Button btnBack;
    TextView txtNameImg;
    Bundle myBackupBundle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myBackupBundle = savedInstanceState;
        setContentView(R.layout.activity_main);
        lstIDImg = new Integer[]{R.drawable.a, R.drawable.b,
                R.drawable.c, R.drawable.d,
                R.drawable.e, R.drawable.f};
        grAlbum = (GridView) findViewById(R.id.grAlbumImage);
        adapter = new MyImageAdapter(this, lstIDImg);
        grAlbum.setAdapter(adapter);
        // Chuyển đổi từ Interge[] sang int [] để truyền qua Intent
        intArray = new int[lstIDImg.length];
        for (int i = 0; i &lt; lstIDImg.length; i++) {
            intArray[i] = lstIDImg[i].intValue();
        }
        //thiết lập sự kiện để mở từng hình ảnh chitiết
        grAlbum.setOnItemClickListener(MainActivity.this);
    }
    @Override
    public void onItemClick(AdapterView&lt;?&gt; adapterView, View view, int i, long l) {
        Intent intent = new Intent(MainActivity.this, ShowImage.class);
        intent.putExtra(“lstIDImn”,intArray);
        intent.putExtra(“posistion”, i);
        this.startActivity(intent);
    }
}

Sau khi đã làm xong ActivityMain, chúng ta sẽ code phần nhận dữ liệu từ ShowImage khi nhấn vào một bức ảnh trên MainActivity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Thanh Tai on 7/22/2016.
*/
public class ShowImage extends AppCompatActivity {
    TextView txtpImage;
    ImageView imgContent;
    Button btnBack;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_item_gridview);
        Bundle extras = getIntent().getExtras();
        int[] lstIDImg = extras.getIntArray(“lstIDImn”);
        int posistion = extras.getInt(“posistion”);
        txtpImage = (TextView) findViewById(R.id.txtNameImg);
        imgContent = (ImageView) findViewById(R.id.imgContent);
        btnBack = (Button) findViewById(R.id.btnBack);
        txtpImage.setText(“Ảnh Số ” + posistion);
        imgContent.setImageResource(lstIDImg[posistion]);
        btnBack.setOnClickListener(Back_click);
    }
    View.OnClickListener Back_click = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    };
}

sau khi đã hoàn thành code, các bạn tiến hành run project sẽ được kết quả như trên.

Vừa rồi mình đã hướng dẫn các bạn hiểu hơn về GridView. Nếu bạn nào đã nắm rõ về ListView thì cũng không khó để hiểu về GridView. Hy vọng với 2 ví dụ trên các bạn đã có thể nắm rõ về loại control này. Chúc các bạn học.

Nếu các bạn muốn biết thêm các kỹ thuật khác về android, các bạn có thể tham khảo thêm các khóa học android tại đây.

Cùng Danh Mục:

Liên Quan Khác

Leave a Reply

Your email address will not be published. Required fields are marked *