BaseAdapter

MainActivity.java

package com.example.hd.baseadapter;

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 MainActivity extends Activity {
    private GridView mGridView;
    private int[] images = {R.drawable.ic_11,R.drawable.ic_12,R.drawable.ic_13,R.drawable.ic_14,
            R.drawable.ic_15,R.drawable.ic_16,R.drawable.ic_17,R.drawable.ic_18,R.drawable.ic_19,R.drawable.ic_20};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setAdapter(new GridBase(MainActivity.this));
    }

    public class GridBase extends BaseAdapter{
        Context context;
        public GridBase(Context c) {
            // TODO Auto-generated constructor stub
            this.context = c;
        }

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

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return images[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 view;
            if(convertView == null){
                view = new ImageView(context); 
            }else{
                view = (ImageView) convertView;
            }
            view.setImageResource(images[position]);
            return view;
        }

    }
}

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

    <GridView  android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="auto_fit" android:columnWidth="90dp" android:stretchMode="columnWidth" android:verticalSpacing="5dp" android:horizontalSpacing="10dp">
    </GridView>

    <ImageView  android:id="@+id/iamgeview" android:layout_width="match_parent" android:layout_height="wrap_content" />

</LinearLayout>

你可能感兴趣的:(BaseAdapter)