<GridView android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="auto_fit" android:horizontalSpacing="5dp" android:verticalSpacing="5dp" android:columnWidth="70dp" />
public class MainActivity extends Activity { private GridView gridview; private int[] resIds = new int[] { R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridview = (GridView) findViewById(R.id.gridview); // 设置gridview显示的adapter MyAdapter adapter = new MyAdapter(); gridview.setAdapter(adapter); } // 使用自定义的adapter class MyAdapter extends BaseAdapter { // 总共有多少元素 @Override public int getCount() { return resIds.length; } // 每个元素的具体内容 @Override public Object getItem(int position) { return resIds[position]; } // 每个元素的id @Override public long getItemId(int position) { return position; } // 每个元素的视图 @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; ViewHolder holder = null; if (convertView == null) { // 1. 从自定义布局中获取view LayoutInflater inflater = LayoutInflater.from(MainActivity.this); view = inflater.inflate(R.layout.item, null); // 2. 在view中找到imageview holder = new ViewHolder(); holder.image = (ImageView) view.findViewById(R.id.imageview); // 3. 绑定view与holder view.setTag(holder); } else { // 1. 从convertView中找到view view = convertView; // 2. 从view中找到绑定的holder holder = (ViewHolder) view.getTag(); } // 4. 给holder中的内容设置值 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resIds[position]); holder.image.setImageBitmap(bitmap); // 5. 返回view return view; } class ViewHolder { public ImageView image; } } }
注:效果类似图片墙