Android UI系统控件进阶(四)—网格视图控件GridView

 网格视图控件GridView

GridView控件视图以二维滚动网格的格式显示其包含的子项控件,这些子项控件全部来自与视图相关的ListAdapter适配器。它位于android.widget包下

源码下载:点击打开链接

Android UI系统控件进阶(四)—网格视图控件GridView_第1张图片


java代码:

public class MainActivity extends Activity {

private GridView gridview = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

this.gridview = (GridView) findViewById(R.id.gridview);
this.gridview.setAdapter(new MyAdapter());
}

class MyAdapter extends BaseAdapter {

int[] images = { R.drawable.photo1, R.drawable.photo2,
R.drawable.photo3, R.drawable.photo4, R.drawable.photo5,
R.drawable.photo6, R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, };

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

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(final int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(MainActivity.this);
iv.setImageResource(this.images[arg0]);
iv.setLayoutParams(new GridView.LayoutParams(85, 85));
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
iv.setPadding(8, 8, 8, 8);
iv.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, arg0+ " ", Toast.LENGTH_SHORT).show();

}
});
return iv;
}

}

xml代码:

<?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:columnWidth="100dp"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center" />

你可能感兴趣的:(android,android,网格视图控件GridView,UI系统控件进阶)