(可以比較另一種視圖, 畫廊(Gallery)).
這次實現一個GridView, 顯示/res內的drawable物件.
先創建一個文件夾/res/drawable, 並複製一些PNG圖形到/res/drawable內. 我使用的文件名為a01.png~a15.png.
修改main.xml, 使用GridView.
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
創建網格視圖(GridView), 需要擴展BaseAdapter創建一個新類ImageAdapter, 並需重寫一些方法, 詳細請參考代碼內容及另一篇文章getView() 和 convertView.
package com.AndroidGridView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class AndroidGridView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView)findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter{
private Context context;
private Integer[] mThumbIds = {
R.drawable.a01,
R.drawable.a02,
R.drawable.a03,
R.drawable.a04,
R.drawable.a05,
R.drawable.a06,
R.drawable.a07,
R.drawable.a08,
R.drawable.a09,
R.drawable.a10,
R.drawable.a11,
R.drawable.a12,
R.drawable.a13,
R.drawable.a14,
R.drawable.a15,
};
public ImageAdapter(Context c){
context = c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(context);
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;
}
}
}
沒有留言:
發佈留言