Android利用GridView加载九宫格菜单

简介: 效果图如下:第一步:布局main.xml文件,这里使用了一个GridView和一个滚动文本控件 第二步:编写SYIT_Index.

效果图如下:


第一步:布局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);
		}
	}
}


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

如果觉得对您有帮助,微信扫一扫支持一下:


相关文章
|
Android开发
Android 13 平板Taskbar加载流程
Android 13 平板Taskbar加载流程
1366 0
|
Android开发
Android 13 Qs面板的加载流程
Android 13 Qs面板的加载流程
Android 13 Qs面板的加载流程
|
6月前
|
API Android开发 数据安全/隐私保护
解决android webview 加载http url 失败 net::ERR_CLEARTEXT_NOT_PERMITTED 错误
解决android webview 加载http url 失败 net::ERR_CLEARTEXT_NOT_PERMITTED 错误
228 0
|
4月前
|
Android开发
[Android]DrawerLayout滑动菜单+NavigationView
[Android]DrawerLayout滑动菜单+NavigationView
26 0
|
4月前
|
XML Java Android开发
Android App手势冲突处理中上下左右滑动的处理以及侧滑边缘菜单的讲解及实战(附源码 可直接使用)
Android App手势冲突处理中上下左右滑动的处理以及侧滑边缘菜单的讲解及实战(附源码 可直接使用)
64 0
|
4月前
|
XML Java Android开发
Android Studio App开发中工具栏Toolbar、溢出菜单OverflowMenu、标签布局TabLayout的讲解及实战(实现京东App的标签导航栏,附源码)
Android Studio App开发中工具栏Toolbar、溢出菜单OverflowMenu、标签布局TabLayout的讲解及实战(实现京东App的标签导航栏,附源码)
58 0
|
4月前
|
XML Java Android开发
Android Studio App开发中异步任务AsynTask与异步服务IntentService的讲解与实战(实现四大名著的加载进度条 附源码)
Android Studio App开发中异步任务AsynTask与异步服务IntentService的讲解与实战(实现四大名著的加载进度条 附源码)
54 0
|
9月前
|
XML Java 数据处理
Android:RecyclerView封装,打造列表极简加载
此库的封装,除了刷新加载库使用了SmartRefreshLayout,其他的都是自己从0到1的开发,目前,自己已经在项目中使用,暂时没有出现任何问题,当然了,后续,也会不断的对其进行优化,增加一些其他的功能,希望有需要的小伙伴,长期关注。
233 0
|
9月前
|
XML Android开发 数据格式
Android上机实验-4 菜单和对话框
Android上机实验-4 菜单和对话框
108 1
|
9月前
|
XML Java 测试技术
【Android开发日常】一文弄懂桌面图标快捷菜单 & 桌面小组件
开发可以定义快捷方式,以便在应用中执行特定操作。 这些快捷方式可在受支持的启动器或助理(如 Google 助理)中显示,方便用户快速启动应用中的常见任务或推荐任务。 通过本文你还将了解一些可提升快捷方式效果的最佳做法。