標籤:find 複製 item column 控制項實現 tco code null 接下來
如下代碼直接複製到項目就可以運行使用了。我們都知道,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="@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 九宮格