GridView 最 简单使用示例。
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:gravity="center_horizontal"
>
<include layout="@layout/top_bar" />
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#FF789977"
/>
<EditText android:id="@+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="输入查询"
android:drawableRight="@drawable/ic_btn_search"
/>
<GridView android:id="@+id/gr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="8dip"
android:verticalSpacing="10dip"
android:numColumns="3"
android:gravity = "center"
android:stretchMode="columnWidth"
android:layout_marginLeft="3dip"
android:layout_marginRight="3dip"
/>
</LinearLayout>
R.cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="90dip"
/>
<TextView android:layout_width="wrap_content"
android:layout_below="@id/image" android:layout_height="wrap_content"
android:text="TextView01" android:layout_centerHorizontal="true"
android:textColor="#FF45b576"
android:id="@+id/itemText">
</TextView>
</RelativeLayout>
代码:
public class mActivity extends Activity {
private List<Map<String,Object> > items;
private int imgIds[] = new int[]{R.drawable.ktv,R.drawable.ktv1,R.drawable.ktv2,
R.drawable.ktv3,R.drawable.ktv4,R.drawable.ktv5,
R.drawable.ktv8,R.drawable.ktv7,R.drawable.ktv6,};
private String ktvnames[] ={"音乐房子","浪漫","匣子Kbox",
"心动KTV","糖果","快乐歌声",
"榕树歌城","好乐迪","欢乐迪"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main5);
items = new ArrayList<Map<String,Object>>();
for ( int i =0; i<imgIds.length; i++){
Map<String,Object> item = new HashMap<String,Object>();
item.put("img", imgIds[i]);
item.put("ktvname", ktvnames[i]);
items.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.cell,
new String[]{"img","ktvname"}, new int[]{R.id.image,R.id.itemText}){
};
GridView gd = (GridView)findViewById(R.id.gr);
gd.setAdapter(adapter);
//滚动滑轮 选择
gd.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
Toast.makeText(mActivity.this, "选中了"+ ktvnames[pos] +"KTV", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
}
}