GridView
和listview用法相似
<GridView
android:id="@+id/gv_home"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:numColumns="3" //有三列
android:verticalSpacing="20dp" >//垂直线间距离
</GridView>
子项布局home_list_item.xml
<ImageView
android:id="@+id/iv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/home_apps" />
<TextView
android:id="@+id/tv_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="@color/black"
android:textSize="18sp"
android:text="手机防盗" />
/**
* 主页面
*
* @author Kevin
*
*/
public class HomeActivity extends Activity {
private GridView gvHome;
private String[] mItems = new String[] { "手机防盗", "通讯卫士", "软件管理", "进程管理",
"流量统计", "手机杀毒", "缓存清理", "高级工具", "设置中心" };
private int[] mPics = new int[] { R.drawable.home_safe,
R.drawable.home_callmsgsafe, R.drawable.home_apps,
R.drawable.home_taskmanager, R.drawable.home_netmanager,
R.drawable.home_trojan, R.drawable.home_sysoptimize,
R.drawable.home_tools, R.drawable.home_settings };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
gvHome = (GridView) findViewById(R.id.gv_home);
gvHome.setAdapter(new HomeAdapter());
}
class HomeAdapter extends BaseAdapter {
@Override
public int getCount() {
return mItems.length;//9个列表
}
@Override
public Object getItem(int position) {
return mItems[position];//返回null也没事
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(HomeActivity.this,
R.layout.home_list_item, null);//将字布局加载进来
ImageView ivItem = (ImageView) view.findViewById(R.id.iv_item);
TextView tvItem = (TextView) view.findViewById(R.id.tv_item);
- //getview会被调用9次
tvItem.setText(mItems[position]);
ivItem.setImageResource(mPics[position]);
return view;
}
}
// 设置监听
gvHome.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
// 手机防盗
showPasswordDialog();
break;
case 8:
// 设置中心
startActivity(new Intent(HomeActivity.this,
SettingActivity.class));
break;
default:
break;
}
}
});
}
时间: 2024-10-15 16:37:19