Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android 交錯 GridView,androidgridview

Android 交錯 GridView,androidgridview

編輯:關於android開發

Android 交錯 GridView,androidgridview


下載 Demo

交錯 GridView


交錯 GridView 只是具有不等大小行、多個列的 GridView。你可能已經使用過 Pinterest,Expedia 或 Etsy Android app。

目前,已經有 2、3 個很不錯的開源庫。

交錯 GridView 庫

  • Staggered GridView by Etsy
  • Staggered GridView by Maurycy Wojtowicz

下面說明最流行使用最廣泛的 Etsy 的交錯 gridview。

Etsy 交錯 GridView


自定義的交錯 GridView 是根據 AbsListView 類擴展的,它當然也就支持 AbsListView.OnScrollListener

功能

  • 可以配置橫向和縱向的列數量。
  • 跨方向變化的異步行位置。
  • 可配置項的邊距(margin)
  • 支持頁眉(header)和頁腳(footer)。
  • 內部填充(Internal padding ),不影響頁眉和頁腳。

Etsy 的交錯 gridview 不支持項的長按事件和選擇器 drawables,而 Maurycy 的交錯 gridview 則支持長按事件。

環境

  • Windows 2008 R2 64 位
  • Eclipse ADT V22.6.2,Android 4.4.2(API 19)
  • SAMSUNG GT-8618,Android OS 4.1.2

項目結構

2014-09-05_111749_副本

圖 1 項目結構

  • StaggeredGrid 項目是 com.etsy.android.grid 庫。
  • StaggeredGridDemo 項目是示例。

示例:Etsy 交錯 GridView

1_副本

圖 2 演示交錯 GridView

  • 下載/包含庫 com.etsy.android.grid

com.etsy.android.grid 庫目前配置為只能通過 Gradle 生成,因此,如果您使用 Android Studio,那麼你可以直接的方式包括這個庫,作為 gradle 依賴來生成。如果你使用 Eclipse/ Ant,那麼你必須執行額外的步驟。

對 Android Studio 環境:

repositories {
    mavenCentral()
}
 
dependencies {
    compile 'com.etsy.android.grid:library:x.x.x' // read below comment
}

對 Eclipse/Ant build:

下載 com.etsy.android.grid,並導入到項目。

  • 把 StaggeredGridView 放到你的布局——activity_sgv.xml
<com.etsy.android.grid.StaggeredGridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/grid_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:column_count="@integer/grid_column_count"
    app:item_margin="8dp" />
  • 為 StaggeredGridView 定義行布局——row_grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/panel_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal" >
 
    <com.etsy.android.grid.util.DynamicHeightImageView
        android:id="@+id/imgView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />
 
</FrameLayout>

自定義行應該包含 DynamicHeightImageView 或 DynamicHeightTextView

  • 自定義 adapter
public class SampleAdapter extends ArrayAdapter<String> {
 
    private static final String TAG = "SampleAdapter";
 
    private final LayoutInflater mLayoutInflater;
    private final Random mRandom;
    private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
 
    public SampleAdapter(Context context, int textViewResourceId,
            ArrayList<String> objects) {
        super(context, textViewResourceId, objects);
        this.mLayoutInflater = LayoutInflater.from(context);
        this.mRandom = new Random();
    }
 
    @Override
    public View getView(final int position, View convertView,
            final ViewGroup parent) {
 
        ViewHolder vh;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.row_grid_item,
                    parent, false);
            vh = new ViewHolder();
            vh.imgView = (DynamicHeightImageView) convertView
                    .findViewById(R.id.imgView);
 
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
 
        double positionHeight = getPositionRatio(position);
 
        vh.imgView.setHeightRatio(positionHeight);
 
        ImageLoader.getInstance().displayImage(getItem(position), vh.imgView);
        return convertView;
    }
 
    static class ViewHolder {
        DynamicHeightImageView imgView;
    }
 
    private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);
        // if not yet done generate and stash the columns height
        // in our real world scenario this will be determined by
        // some match based on the known height and width of the image
        // and maybe a helpful way to get the column height!
        if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
            Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
        }
        return ratio;
    }
 
    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5
                                                    // the width
    }
}

自定義 adapter 類用來在交錯 GridView 中顯示動態高度的圖片。另外,還使用了 Universal image loader 庫用來異步加載圖片。

  • 把自定義 adapter 設置給 StaggeredGridView
public class StaggeredGridActivity extends Activity implements
        AbsListView.OnScrollListener, AbsListView.OnItemClickListener {
 
    private static final String TAG = "StaggeredGridActivity";
    public static final String SAVED_DATA_KEY = "SAVED_DATA";
 
    private StaggeredGridView mGridView;
    private boolean mHasRequestedMore;
    private SampleAdapter mAdapter;
 
    private ArrayList<String> mData;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sgv);
 
        setTitle("TechnoTalkative - SGV Demo");
        mGridView = (StaggeredGridView) findViewById(R.id.grid_view);
        mAdapter = new SampleAdapter(this, android.R.layout.simple_list_item_1,
                generateData());
        // do we have saved data?
        if (savedInstanceState != null) {
            mData = savedInstanceState.getStringArrayList(SAVED_DATA_KEY);
        }
 
        if (mData == null) {
            mData = generateData();
        }
 
        for (String data : mData) {
            mAdapter.add(data);
        }
 
        mGridView.setAdapter(mAdapter);
        mGridView.setOnScrollListener(this);
        mGridView.setOnItemClickListener(this);
    }
 
    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putStringArrayList(SAVED_DATA_KEY, mData);
    }
 
    @Override
    public void onScrollStateChanged(final AbsListView view,
            final int scrollState) {
        Log.d(TAG, "onScrollStateChanged:" + scrollState);
    }
 
    @Override
    public void onScroll(final AbsListView view, final int firstVisibleItem,
            final int visibleItemCount, final int totalItemCount) {
        Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem
                + " visibleItemCount:" + visibleItemCount + " totalItemCount:"
                + totalItemCount);
        // our handling
        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                Log.d(TAG, "onScroll lastInScreen - so load more");
                mHasRequestedMore = true;
                onLoadMoreItems();
            }
        }
    }
 
    private void onLoadMoreItems() {
        final ArrayList<String> sampleData = generateData();
        for (String data : sampleData) {
            mAdapter.add(data);
        }
        // stash all the data in our backing store
        mData.addAll(sampleData);
        // notify the adapter that we can update now
        mAdapter.notifyDataSetChanged();
        mHasRequestedMore = false;
    }
 
    private ArrayList<String> generateData() {
        ArrayList<String> listData = new ArrayList<String>();
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_2iitkhx.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_w0omeb.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_w9iu1d.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_iw6kh2.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_ru08c8.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_k12r10.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_2e3daug.jpg");
        listData.add("http://images.cnblogs.com/cnblogs_com/liuning8023/610092/o_2igznfr.jpg");
 
        return listData;
    }
 
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view,
            int position, long id) {
        Toast.makeText(this, "Item Clicked: " + position, Toast.LENGTH_SHORT)
                .show();
    }
}

表 1 交錯 GridView 可配置的屬性

屬性

說明

item_margin The margin around each grid item (default 0dp). column_count The number of columns displayed. Will override column_count_portrait and column_count_landscape if present (default 0). column_count_portrait The number of columns displayed when the grid is in portrait (default 2). column_count_landscape The number of columns displayed when the grid is in landscape (default 3). grid_paddingLeft Padding to the left of the grid. Does not apply to headers and footers (default 0). grid_paddingRight Padding to the right of the grid. Does not apply to headers and footers (default 0). grid_paddingTop Padding to the top of the grid. Does not apply to headers and footers (default 0). grid_paddingBottom Padding to the bottom of the grid. Does not apply to headers and footers (default 0).

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved