GridView實現方塊佈局

石曼迪發表於2016-08-22

效果如下:

image

先建立一個BaseViewHolder 

package com.example.griddemo;

import android.util.SparseArray;
import android.view.View;

public class BaseViewHolder {
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }

}
View Code

然後建立MyGridAdapter 

package com.example.griddemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class MyGridAdapter extends BaseAdapter {
    private Context mContext;

    public String[] img_text = { "轉賬", "餘額寶", "手機充值", "信用卡還款", "淘寶電影", "彩票",
            "當面付", "親密付", "機票", };
    public int[] imgs = { R.drawable.app_transfer, R.drawable.app_fund,
            R.drawable.app_phonecharge, R.drawable.app_creditcard,
            R.drawable.app_movie, R.drawable.app_lottery,
            R.drawable.app_facepay, R.drawable.app_close, R.drawable.app_plane };

    public MyGridAdapter(Context mContext) {
        super();
        this.mContext = mContext;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return img_text.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.grid_item, parent, false);
        }
        TextView tv = BaseViewHolder.get(convertView, R.id.tv_item);
        ImageView iv = BaseViewHolder.get(convertView, R.id.iv_item);
        iv.setBackgroundResource(imgs[position]);

        tv.setText(img_text[position]);
        return convertView;
    }

}
View Code

建立MyGridView 

package com.example.griddemo;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
/**
 * @Description:解決在scrollview中只顯示第一行資料的問題
 */
public class MyGridView extends GridView {
    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }


}
View Code

MainActivity的實現如下: 

package com.example.griddemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private MyGridView gridview;
    private Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = MainActivity.this;
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        gridview=(MyGridView) findViewById(R.id.gridview);
        gridview.setAdapter(new MyGridAdapter(this));

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                Toast.makeText(mContext,""+id,Toast.LENGTH_SHORT).show();
                //Toast.makeText(mContext, "你點選了第" + position + "項", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
View Code

最後建立檢視部分:

Grid_item部分如下: 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_margin="0.0dip"
    android:background="@color/griditems_bg" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:background="@drawable/bg_gv"
        android:padding="12.0dip" >

        <ImageView
            android:id="@+id/iv_item"
            android:layout_width="58.0dip"
            android:layout_height="58.0dip"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/app_name" />

        <TextView
            android:id="@+id/tv_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/iv_item"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5.0dip"
            android:maxLines="1"
            android:textColor="@color/commo_text_color"
            android:textSize="14.0sp" />
    </RelativeLayout>

</RelativeLayout>
View Code

activity_main部分如下:

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

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:scrollbars="none" >

        <com.example.griddemo.MyGridView
            android:id="@+id/gridview"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:horizontalSpacing="0.0dip"
            android:listSelector="@null"
            android:numColumns="3"
            android:scrollbars="none"
            android:stretchMode="columnWidth"
            android:verticalSpacing="0.0dip" />
    </ScrollView>

</LinearLayout>
View Code

完整程式碼下載

 

 

相關文章