---
# System prepended metadata

title: GridView
tags: [介紹]

---

GridView
===

[toc]

### EX1: 搭配 `ArrayAdapter`
```java=
package com.example.myapplication2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private String[] fruits = {"Apple","Banana","Orange","Grape","Strawberry"};

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

        GridView gvShow = (GridView) findViewById(R.id.gvShow);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                MainActivity.this,
                android.R.layout.simple_list_item_1,
                fruits
        );
        gvShow.setAdapter(adapter);

        gvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick
                    (AdapterView<?> adapterView, View view, int position, long id) {
                String msg = adapterView.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


```

```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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <GridView
        android:id="@+id/gvShow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2" />
</androidx.constraintlayout.widget.ConstraintLayout>
```

![](https://i.imgur.com/HLo6464.png)

### EX2: 搭配 `BaseAdapter` 

有調整一下範例的code，將資料的類別、繼承 `BaseAdapter` 的類別都分別獨立出來

* 資料類別：`Fruit.java`
```java=
...

public class Fruit {
    private String name;
    private int price;
    private int img;

    Fruit(String name,int price,int img){
        this.name=name;
        this.price=price;
        this.img=img;
    }

    public void setName(String name) {
        this.name = name;
    }

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

    public void setImg(int img) {
        this.img = img;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    public int getImg() {
        return img;
    }
}
``` 

* 繼承 `BaseAdapter` 類別：`FruitAdapter.java`

```java=
...

public class FruitAdapter extends BaseAdapter {
    private List<Fruit> fruitList = new ArrayList<>();
    private Context context;

    FruitAdapter(Context context, List<Fruit> fruitList) {
        this.context = context;
        this.fruitList = fruitList;
    }

    @Override
    public int getCount() {
        return fruitList.size();
    }

    @Override
    public Object getItem(int position) {
        return fruitList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return fruitList.get(position).getImg();
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        View gridview = view;
        LayoutInflater inflater = LayoutInflater.from(context);

        if (gridview == null) {
            gridview = inflater.inflate(R.layout.fruit_layout, null);
        }
        Fruit fruit = fruitList.get(position);
        TextView tvName = (TextView) gridview.findViewById(R.id.tvName);
        tvName.setText(fruit.getName());
        TextView tvPrice = (TextView) gridview.findViewById(R.id.tvPrice);
        tvPrice.setText(Integer.toString(fruit.getPrice()));
        ImageView imgFruit = (ImageView) gridview.findViewById(R.id.imgFruit);
        imgFruit.setImageResource(fruit.getImg());
        return gridview;
    }
}

```

* 主程式：`MainActivity.java`

```java=
...

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();
    private GridView gvShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        fruitList=getList();
        setAdapter();
        setListener();
    }

    private void findViews () {
        gvShow = (GridView) findViewById(R.id.gvShow);
    }

    private void setToast (int position){
        Toast.makeText(MainActivity.this,fruitList.get(position).getName(), Toast.LENGTH_SHORT).show();
    }

    private void setAdapter() {
        FruitAdapter adapter = new FruitAdapter(this, fruitList);
        gvShow.setAdapter(adapter);
    }

    private void setListener() {
        gvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                setToast(position);
            }
        });
    }

    private List<Fruit> getList () {
        fruitList.add(new Fruit("Apple", 50, R.drawable.num1));
        fruitList.add(new Fruit("Banana", 20, R.drawable.num2));
        fruitList.add(new Fruit("Orange", 30, R.drawable.num3));
        fruitList.add(new Fruit("Grape", 100, R.drawable.num1));
        fruitList.add(new Fruit("Strawberry", 120, R.drawable.num2));
        return fruitList;
    }
}
```

* layout UI：`activity_main.xml`

```xml=
<?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"
    tools:context=".MainActivity">

    <GridView
        android:id="@+id/gvShow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="2" />
</LinearLayout>
```

* itemView UI：`fruit_layout.xml`

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

    <ImageView
        android:id="@+id/imgFruit"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp" />

    <TextView
        android:id="@+id/tvPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

</LinearLayout>
```

![](https://i.imgur.com/BRCBs7Y.png)


## Ref.

[https://ithelp.ithome.com.tw/articles/10220137](https://ithelp.ithome.com.tw/articles/10220137)

[https://ithelp.ithome.com.tw/articles/10220628](https://ithelp.ithome.com.tw/articles/10220628)

###### tags: `介紹`