Android API文檔 GridView

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.

For an introduction to how you can dynamically insert views using an adapter, read Building Layouts with an Adapter.

GridView 是一個通過二維的具有滾動效果的網頁格子來展示我們的每一個條目,這些網頁格子可以通過使用ListAdapter來實現自動的將這些格子自動插入到佈局之中。

爲了進一步的瞭解如何使用動態通過適配器來插入數據,請閱讀Building Layouts with an Adapter.這個在後期將會更。


Example


In this tutorial, you'll create a grid of image thumbnails. When an item is selected, a toast message will display the position of the image.

  1. Start a new project named HelloGridView.
  2. Find some photos you'd like to use, or download these sample images. Save the image files into the project's res/drawable/ directory.
  3. Open the res/layout/main.xml file and insert the following:
翻譯實例:

在這篇的引導中,你就會創造出一個帶有圖片碎片的網格,當一個條目被選擇之後,將會有一個土司消息被展示在這個圖片的位置,首先創建一個命名爲HellowGridView的工程,然後找一些自己喜歡的圖片放在圖片目錄下,然後就是佈局文件

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

這裏有幾個需要解釋一下的屬性,那就是numColumns這個屬性,這個屬性表示的是每一個行格子的數目,然後還有比一個屬性就是stretchMode這個屬性,這個屬性表示的是格子的縮放效果,這裏的設置是隨着寬度進行自動的縮放。

Open HelloGridView.java and insert the following code for the onCreate() method:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

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

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View
 v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

After the main.xml layout is set for the content view, the GridView is captured from the layout withfindViewById(int). The setAdapter() method then sets a custom adapter (ImageAdapter) as the source for all items to be displayed in the grid. The ImageAdapter is created in the next step.

To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a newAdapterView.OnItemClickListener. This anonymous instance defines the onItemClick() callback method to show a Toast that displays the index position (zero-based) of the selected item (in a real world scenario, the position could be used to get the full sized image for some other task).

通過佈局文件設置好內容的視圖之後,我們可以通過findViewById來捕捉到這個GridView,然後這個setAdapter這個方法設置一個常規的適配器一個圖片適配器來作爲每一個要展示的格子的資源文件,接下來我們會創建一個圖片適配器,爲了做一些操作,在這個格子被點擊上之後,可以通過setOnItemClickListener來進行設置,通過這個方法,我們可以展示一個土司展示在我們選擇的圖片的座標位置。

Create a new class called ImageAdapter that extends BaseAdapter:

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

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

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7,
            R.drawable.sample_0, R.drawable.sample_1,
            R.drawable.sample_2, R.drawable.sample_3,
            R.drawable.sample_4, R.drawable.sample_5,
            R.drawable.sample_6, R.drawable.sample_7
    };
}

First, this implements some required methods inherited from BaseAdapter. The constructor and getCount()are self-explanatory. Normally, getItem(int) should return the actual object at the specified position in the adapter, but it's ignored for this example. Likewise, getItemId(int) should return the row id of the item, but it's not needed here.

The first method necessary is getView(). This method creates a new View for each image added to theImageAdapter. When this is called, a View is passed in, which is normally a recycled object (at least after this has been called once), so there's a check to see if the object is null. If it is null, an ImageView is instantiated and configured with desired properties for the image presentation:

  • setLayoutParams(ViewGroup.LayoutParams) sets the height and width for the View—this ensures that, no matter the size of the drawable, each image is resized and cropped to fit in these dimensions, as appropriate.
  • setScaleType(ImageView.ScaleType) declares that images should be cropped toward the center (if necessary).
  • setPadding(int, int, int, int) defines the padding for all sides. (Note that, if the images have different aspect-ratios, then less padding will cause more cropping of the image if it does not match the dimensions given to the ImageView.)

If the View passed to getView() is not null, then the local ImageView is initialized with the recycled View object.

At the end of the getView() method, the position integer passed into the method is used to select an image from the mThumbIds array, which is set as the image resource for the ImageView.

All that's left is to define the mThumbIds array of drawable resources.

首先這個工具類需要繼承許多來自BaseAdapter的方法,這個構造器和getCout的方法是比較簡單的,無須在此進行解釋,通常getItem這個方法需要返回一個實體在這個適配器中的具體的位置,但是這忽略了一個實例,那就是例如,getItemId這個方法需要的是返回這個條目的行號,但是這裏並不需要。

第一個最重要的方法時getView(),這個方法創造出了一個View對每一個添加到圖片適配器中的圖片,當這個方法被調用的時候,就會有一個view產生,通常這是一個可以回收的實體,所以這裏有一個檢測,如果檢測到了是空,那麼就會有一個ImageView被初始化成型帶着所需要的屬性來展示一個圖片。

下面是幾個方法:

setLayoutParams(ViewGroup.LayoutParams)通過這個方法我們可以設置視圖的高度和寬度,這個確保了無論圖片是有多大,都可以重新定義其大小然後合適的將其展現出來。

setScaleType(ImageView.ScaleType)這個方法聲明一個圖片如果在必要的情況下會出現在中心。

setPadding(int,int,int,int)這個定義了各個方向上邊界上的距離,(注意,如果這個圖片有不同的寬高比,然後沒有間距,如果沒有適應各個方向的話)

如果View通過了getView()的這個方法之後,如果不是空的話,就會有一個本地的圖片初始化給已經被回收的view實例,在這個方法的最後,我們會根據位置座標選擇圖片資源進行展示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章