.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/gv_1"
    android:numColumns="4"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:columnWidth="120dp"
    android:gravity="center"
    android:stretchMode="columnWidth">

</GridView>

.java

package com.hanqi.application3;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class UIActivity6 extends AppCompatActivity {
    int[] imid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ui6);

        GridView gv_1= (GridView)findViewById(R.id.gv_1);
        imid =new int[] {R.drawable.an1,R.drawable.an2,R.drawable.an3,
                R.drawable.an1,R.drawable.an2,R.drawable.an3,
                R.drawable.an1,R.drawable.an2,R.drawable.an3};

        gv_1.setAdapter(new MyBaseAdapter());

        gv_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(UIActivity6.this, "position =" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

    class MyBaseAdapter extends BaseAdapter
    {
        @Override
        public int getCount() {
            return imid.length;
        }

        @Override
        public Object getItem(int position) {
            return imid[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            //获取数据
            int Imageid = imid[position];
            ImageView iv1 = null;
            //构造视图
            if (convertView == null)
            {
                iv1= new ImageView(UIActivity6.this);
                //设置属性setLayoutParams
                iv1.setLayoutParams(new GridView.LayoutParams(120,120));
                iv1.setScaleType(ImageView.ScaleType.FIT_XY);

            }
            else
            {
                iv1 = (ImageView)convertView;
            }


            iv1.setImageResource(Imageid);

            return iv1;
        }
    }
}

 

posted on 2016-04-07 22:37  让心开始  阅读(223)  评论(0编辑  收藏  举报