Android 九宫格

青春须早为,岂能长少年。这篇文章主要讲述Android 九宫格相关的知识,希望能为你提供帮助。
如下代码直接复制到项目就可以运行使用了。我们都知道,android的九宫格可以用GridView控件实现,这里首先定义一个
gridview.xml

< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > < GridView android:id="@+id/gv_home" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="3" > < /GridView> < /LinearLayout>

接着还得在定义一个gridview_item.xml
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" > < ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iv_icon" android:src="https://www.songbingjia.com/android/@drawable/ic_launcher" /> < TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_title" android:text="模块标题" android:textSize="18sp" /> < /LinearLayout>

那么现在布局就实现了,接下来就是Android代码了。这里需要注意的就是不能缺少GridView适配器。

public class MainActivity extends Activity { private GridView gv_home; private String[] mTitleStrs; private int[] mDrawableIds; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); initUI(); //初始化数据的方法 initData(); }private void initData() {mTitleStrs = new String[]{"1","2","3","4", "5","6","7","8","9"}; //注意这里的数字要和下面的图片id一一对应,要不然实现的效果会文字图片不符合 mDrawableIds = new int[]{R.drawable.ic_launcher,R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher}; //九宫格控件设置数据适配器(等同ListView数据适配器) gv_home.setAdapter(new MyAdapter()); }class MyAdapter extends BaseAdapter{@Override public int getCount() { return mTitleStrs.length; }@Override public Object getItem(int position) { return mTitleStrs[position]; }@Override public long getItemId(int position) { return position; }@Override public View getView(int position, View convertView, ViewGroup parent) { View view = View.inflate(getApplicationContext(), R.layout.gridview_item, null); ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon); TextView tv_title = (TextView) view.findViewById(R.id.tv_title); tv_title.setText(mTitleStrs[position]); iv_icon.setBackgroundResource(mDrawableIds[position]); return view; } } private void initUI() { gv_home = (GridView) findViewById(R.id.gv_home); } }

【Android 九宫格】 

    推荐阅读