Android课程---关于GridView网格视图的学习
activity_ui6.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="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:columnWidth="100dp" android:gravity="center" android:stretchMode="columnWidth"> <!--stretchMode:缩放模式 columnWidth:根据列宽来设--> </GridView>
UIActivity6.java
package com.hanqi.test5; 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.yuantu,R.drawable.yuantu,R.drawable.yuantu,R.drawable.yuantu,R.drawable.yuantu ,R.drawable.yuantu,R.drawable.yuantu,R.drawable.yuantu}; 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 iv_1 = null; if (convertView == null) { iv_1 = new ImageView(UIActivity6.this); iv_1.setLayoutParams(new GridView.LayoutParams(100,100)); //属性设置 iv_1.setScaleType(ImageView.ScaleType.FIT_XY); //FIT_XY:自动全部充满 } else { iv_1 = (ImageView)convertView; //强转 } iv_1.setImageResource(Imageid); return iv_1; } } }
效果图如下(因图片本身是长方形的,用网格视图缩放成了正方形,有点不好看):
网格视图的总结: