Android利用GridView載入九宮格選單

暖楓無敵發表於2014-10-09

效果圖如下:


第一步:佈局main.xml檔案,這裡使用了一個GridView和一個滾動文字控制元件


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/backsmall"
    android:orientation="vertical" >
    <GridView
        android:id="@+id/GridView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:columnWidth="90dip"
        android:gravity="center"
        android:horizontalSpacing="10dip"
        android:numColumns="3"
        android:verticalSpacing="10dip" >
    </GridView>


<cn.superyouth.www.itools.MarqueeText
    android:id="@+id/textMsg" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"        
    android:layout_marginTop="115dp"         
    android:textColor="@android:color/black" 
    android:lines="1"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:scrollHorizontally="true"  
    android:marqueeRepeatLimit="marquee_forever"  
    android:ellipsize="marquee" 
    />


</LinearLayout>



第二步:編寫SYIT_Index.java檔案,繼承自Activity類


package cn.superyouth.www;


import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import cn.superyouth.www.SYIT_SSJC.ReadHttpGet;
import cn.superyouth.www.itools.MarqueeText;
import cn.superyouth.www.itools.MenuItem;
import cn.superyouth.www.itools.Tools_AppAdapter;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class SYIT_Index extends Activity {
	MarqueeText autoScrollTextView;
	StringBuilder builder = new StringBuilder();
	public static String WARN_MSG = "";
	private TextView text = null;
	boolean isError = false;


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);


		GridView gridview = (GridView) findViewById(R.id.GridView);

		// 新增選單
		ArrayList<MenuItem> map = new ArrayList<MenuItem>();
		for (int i = 1; i < 10; i++) {
			if (i == 1) {
				MenuItem item = new MenuItem();
				item.title = "實時監測";
				item.iconId = R.drawable.m1;
				map.add(item);
			}
			if (i == 3) {
				MenuItem item = new MenuItem();
				item.title = "預警資訊";
				item.iconId = R.drawable.m2;
				map.add(item);
			}
			if (i == 2) {
				MenuItem item = new MenuItem();
				item.title = "視訊監控";
				item.iconId = R.drawable.m3;
				map.add(item);
			}
			if (i == 4) {
				MenuItem item = new MenuItem();
				item.title = "統計查詢";
				item.iconId = R.drawable.m4;
				map.add(item);
			}
			if (i == 5) {
				MenuItem item = new MenuItem();
				item.title = "災情上報";
				item.iconId = R.drawable.m5;
				map.add(item);
			}
			if (i == 6) {
				MenuItem item = new MenuItem();
				item.title = "衛星雲圖";
				item.iconId = R.drawable.m6;
				map.add(item);
			}
			if (i == 7) {
				MenuItem item = new MenuItem();
				item.title = "線上幫助";
				item.iconId = R.drawable.m7;
				map.add(item);
			}
			if (i == 8) {
				MenuItem item = new MenuItem();
				item.title = "氣象雷達";
				item.iconId = R.drawable.m8;
				map.add(item);
			}
			if (i == 9) {
				MenuItem item = new MenuItem();
				item.title = "關於我們";
				item.iconId = R.drawable.m9;
				map.add(item);
			}
		}


		Tools_AppAdapter adapter = new Tools_AppAdapter(this, map,
				R.layout.item, new String[] { "ItemImage", "ItemText" },
				new int[] { R.id.ItemImage, R.id.ItemText }); // 對應R的Id


		gridview.setAdapter(adapter);

		// 新增點選事件
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MenuItem item = (MenuItem) arg0.getItemAtPosition(arg2);
				// Toast用於向使用者顯示一些幫助/提示


				if (item.title.equals("實時監測")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_SSJC.class);
					startActivity(intent);
				}
				if (item.title.equals("預警資訊")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_Warning.class);
					startActivity(intent);
				}
				if (item.title.equals("視訊監控")) {
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_LAUNCHER);
					// 上面ComponentName有兩個引數 第一個引數 :包名 第二個引數:類的命名
					ComponentName comp = new ComponentName(
							"com.mm.android.direct.gdmssphoneLite",
							"com.mm.android.direct.gdmssphoneLite.SplashActivity");
					intent.setComponent(comp);
					intent.setAction("android.intent.action.VIEW");
					startActivity(intent);
				}
				if (item.title.equals("統計查詢")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_TJCX.class);
					startActivity(intent);
				}
				if (item.title.equals("災情上報")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_PictureUpload.class);
					startActivity(intent);
				}
				if (item.title.equals("衛星雲圖")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this,
							SYIT_SatelliteCloudChart.class);
					startActivity(intent);
				}
				if (item.title.equals("線上幫助")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_OnlineHelp.class);
					startActivity(intent);
				}
				if (item.title.equals("氣象雷達")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_WeatherRadar.class);
					startActivity(intent);
				}
				if (item.title.equals("關於我們")) {
					Intent intent = new Intent();
					intent.setClass(SYIT_Index.this, SYIT_AboutUs.class);
					startActivity(intent);
				}
			}


		});


		// 開啟執行緒
		new Thread() {
			@Override
			public void run() {
				try {

				} catch (Exception e) {
					isError = true;
					System.out.println(e.toString());
				}
				handler.sendEmptyMessage(0);


			}
		}.start();

		autoScrollTextView = (MarqueeText) findViewById(R.id.textMsg);
		autoScrollTextView.setTextSize(30);
		
		// 點選預警提示資訊,進入預警資訊頁面
		autoScrollTextView.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// 進入預警資訊頁面
				Intent intent = new Intent(SYIT_Index.this, SYIT_Warning.class);
				startActivity(intent);
			}
		});
	}


	/**
	 * 用Handler來更新UI
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (isError) {
				// 建立提示
				Dialog alertDialog = new AlertDialog.Builder(SYIT_Index.this)
						.setTitle("提示").setMessage("伺服器無響應,請稍候再試!")
						.setIcon(R.drawable.ic_launcher).create();
				alertDialog.show();
			} else {
				// 獲取預警資訊
				new ReadHttpGet3()
						.execute("http://61.190.32.10/CityLowerRoadSys/ashx/yjxx.ashx");
			}
		}
	};


	@SuppressLint("Override")
	class ReadHttpGet3 extends AsyncTask<Object, Object, Object> {
		@Override
		protected Object doInBackground(Object... params) {
			HttpGet httpRequest = new HttpGet(params[0].toString());
			try {
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse httpResponse = httpClient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String strResult = EntityUtils.toString(httpResponse
							.getEntity());
					return strResult;
				} else {
					return "請求出錯";
				}
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}


		protected void onCancelled(Object result) {
			super.onCancelled();
		}


		@SuppressLint("Override")
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			try {
				// 建立一個JSON物件
				JSONObject jsonObject = new JSONObject(result.toString())
						.getJSONObject("parent");
				// 獲取某個物件的JSON陣列
				JSONArray jsonArray = jsonObject.getJSONArray("children");


				for (int i = 0; i < jsonArray.length(); i++) {
					// 新建一個JSON物件,該物件是某個陣列裡的其中一個物件
					JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
					builder.append(jsonObject2.getString("name") + " ");
					WARN_MSG += jsonObject2.getString("name") + " ";
				}
				System.out.println(builder.toString());
				if (builder.toString().length() == 0) {
					autoScrollTextView.setTextColor(Color.BLUE);
					autoScrollTextView.setText("暫無任何預警資訊!");
				} else {
					autoScrollTextView.setTextColor(Color.RED);
					autoScrollTextView.setText(builder.toString());
				}


			} catch (JSONException e) {
				e.printStackTrace();
			}
		}


		protected void onPreExecute() {
			// Toast.makeText(getApplicationContext(),
			// "開始HTTP GET請求",Toast.LENGTH_LONG).show();
		}


		protected void onProgressUpdate(Object... values) {
			super.onProgressUpdate(values);
		}
	}
}


===========================================================================

如果覺得對您有幫助,微信掃一掃支援一下:


相關文章