【Android】九宮格的實現

第一步,佈局文件html


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".JokeTabHostActivity"
    android:orientation="vertical"
    >
	
    <GridView 
        android:id="@+id/GridView"
        android:listSelector="@android:color/transparent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:layout_marginTop="10dp"
        android:stretchMode="columnWidth">
    </GridView>

</LinearLayout>

第二步,在你的activity  中調用初始化Grid

GridView gridview = (GridView) findViewById(R.id.GridView);
		ArrayList<HashMap<String, Object>> meumList = new ArrayList<HashMap<String, Object>>();
		for (int i = 1; i < 4; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			if (i == 1) {
				map.put("ItemImage", R.drawable.a1);
				map.put("ItemText", "文章精選");
			} else if (i == 2) {
				map.put("ItemImage", R.drawable.a2);
				map.put("ItemText", "幽默笑話");
			} else {
				map.put("ItemImage", R.drawable.a5);
				map.put("ItemText", "期待更多");
			}

			meumList.add(map);
		}

		SimpleAdapter saItem = new SimpleAdapter(this, meumList, // 數據源
				R.layout.item, // xml實現
				new String[] { "ItemImage", "ItemText" }, // 對應map的Key
				new int[] { R.id.ItemImage, R.id.ItemText }); // 對應R的Id
																// //添加Item到網格中
		gridview.setAdapter(saItem); // 添加點擊事件
		gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@SuppressWarnings("static-access")
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int index = arg2 + 1;// id是從0開始的,因此須要+1
				if (index == 1) {
					
						Intent intent = new Intent();
						intent.setClass(MainActivity.this,
								CloseTabHostActivity.class);
						startActivity(intent);
					
					

				}
				if (index == 2) {
					 Intent intent = new Intent();
					 intent.setClass(MainActivity.this,
							 XListViewActivity.class);
					 startActivity(intent);
					//showInfo("正在努力碼代碼中。。。");
					// finish();//中止當前的Activity,若是不寫,則按返回鍵會跳轉回原來的Activity
				}
				if (index == 3) {
					showInfo("期待你的建議,好建議請Q 649175826");
				}
			}
		});


版權聲明:本文爲博主原創文章,未經博主容許不得轉載。java

相關文章
相關標籤/搜索