Android切近實戰(七)

邊看世界盃,邊寫博客。記得小時候,去山上玩,翻了兩座山,到了一個叫克勞的地方。那裏每到六月份,桃子,杏多的很,有時候你坐在樹上吃一下午都不會有人來,天然了,那裏也就人煙稀少。我當時渴急了,在玉米地邊上的牛踩出的蹄窩裏喝了一口水,那水真是甘甜哪,突然以爲腳底下什麼在動,擡腳一看,一隻螃蟹被我踩到了泥土中。那時候吃野棗,自制槍打野雞,用套套野兔,在河裏捉螃蟹,釣魚,在洪水中游泳,上山挖藥,在山上烤紅薯,烤玉米,到了冬天,能夠點荒,一盒火柴去見識燎原,這都是常常的事。不知道如今我再去那地方還能不能能夠去作這些事情,下週準備回去玩玩,看這些地方是否依然仍是那麼美麗。
java


OK,今天咱們來看一下以下這個消息管理界面android

wKioL1OdEoLyBmqiAAHsoBL72HM964.jpg

先上圖,看一下android版本的,先登陸,登錄界面美化以後還像這麼回事web

wKioL1OdEx6CjQtsAAGC-Gl14oI082.jpg

咱們看一下短消息管理界面c#

wKiom1OdE8-wfA_9AAHGCzE8e5s273.jpg


在這裏咱們仍是要首先看一下WebService端數組

public class MessageMng : System.Web.Services.WebService
    {
        [WebMethod]
        public List<MessageEntity> GetMessageEntity(string sendUser, string receiveUser, string title, string messageType, string startDate, string endDate)
        {
            try
            {
                return MessageMngBiz.GetInstance().GetMessageEntity(sendUser, receiveUser, title, messageType, startDate, endDate);
            }
            catch
            {
                return new List<MessageEntity>();
            }

        }
    }

咱們再看一下Biz層ide

public class MessageMngBiz
    {
        static MessageMngBiz messageMngBiz = new MessageMngBiz();
        private MessageMngBiz()
        { }

        public static MessageMngBiz GetInstance()
        {
            return messageMngBiz;
        }

        public List<MessageEntity> GetMessageEntity(string sendUser, string receiveUser, string title, string messageType, string startDateStr, string endDateStr)
        {
            DateTime startDate = DateTime.MinValue;
            DateTime endDate = DateTime.MinValue;
            if (!string.IsNullOrWhiteSpace(startDateStr))
            {
                DateTime.TryParse(startDateStr.Trim(), out startDate);
            }

            if (!string.IsNullOrWhiteSpace(endDateStr))
            {
                DateTime.TryParse(endDateStr.Trim(), out endDate);
            }

            return MessageMngDAL.GetInstance().GetMessageEntity(sendUser, receiveUser, title, messageType, startDate == DateTime.MinValue ? null : (DateTime?)startDate, endDate == DateTime.MinValue ? null : (DateTime?)endDate);
        }
    }

再看一下DAL佈局

 public class MessageMngDAL
    {
        static MessageMngDAL messageMngDAL = new MessageMngDAL();
        private MessageMngDAL()
        { }

        public static MessageMngDAL GetInstance()
        {
            return messageMngDAL;
        }

        /// <summary>
        ///獲取短信息
        /// </summary>
        /// <param name="sendUser">發送者</param>
        /// <param name="receiveUser">接收者</param>
        /// <param name="title">標題</param>
        /// <param name="messageType">類型(未讀/已讀,已刪)</param>
        /// <param name="startDate">開始時間</param>
        /// <param name="endDate">結束時間</param>
        /// <returns></returns>
        public List<MessageEntity> GetMessageEntity(string sendUser, string receiveUser, string title, string messageType, DateTime? startDate, DateTime? endDate)
        {
            bool isDateSearch = startDate.HasValue && endDate.HasValue;

            DirectSpecification<Message> commonSpecification = new DirectSpecification<Message>(msg =>
              (string.IsNullOrEmpty(sendUser) ? true : msg.CerateUser == sendUser)
              && (string.IsNullOrEmpty(title) ? true : msg.Title.Contains(title))
              && (isDateSearch ? (msg.CreateDate >= startDate && msg.CreateDate <= endDate) : true)
              && msg.ReceiveUser.Equals(receiveUser));

            MessageType messageTypeEnum = new MessageTypeIndexes()[messageType];

            using (BonusEntities bonusEntities = new BonusEntities())
            {
                if (messageTypeEnum == MessageType.READ)
                {
                    DirectSpecification<Message> readMsgSpec = new DirectSpecification<Message>(msg => msg.IsDel == false);
                    AndSpecification<Message> andSpecification = new AndSpecification<Message>(commonSpecification, readMsgSpec);

                    IEnumerable<Message> messageList = bonusEntities.Message.Where(andSpecification.SatisfiedBy());

                    return messageList.AsEnumerable().Select(msg =>
                    new MessageEntity()
                    {
                        TransactionNumber = msg.TransactionNumber,
                        Title = msg.Title,
                        MessageContent = msg.MessageContent.Length>50? msg.MessageContent.Substring(0, 50):msg.MessageContent,
                        CreateUser = msg.UserCreate.UerInfo != null ? msg.UserCreate.UerInfo.FirstOrDefault().Name : msg.UserCreate.UseNo,
                        CreateDate = msg.CreateDate.ToString(),
                        IsRead = msg.IsRead
                    }).ToList();
                }

                if (messageTypeEnum == MessageType.DELETE)
                {
                    DirectSpecification<Message> delMsgSpec = new DirectSpecification<Message>(msg => msg.IsDel == true
                    && msg.IsDestroy == false);
                    AndSpecification<Message> andSpecification = new AndSpecification<Message>(commonSpecification, delMsgSpec);

                    IQueryable<Message> messageList = bonusEntities.Message.Where(andSpecification.SatisfiedBy());

                    return messageList.AsEnumerable().Select(msg =>
                    new MessageEntity()
                    {
                        TransactionNumber = msg.TransactionNumber,
                        Title = msg.Title,
                        MessageContent = msg.MessageContent.Substring(0, 50),
                        CreateUser = msg.UserCreate.UerInfo != null ? msg.UserCreate.UerInfo.FirstOrDefault().Name : msg.UserCreate.UseNo,
                        CreateDate = msg.CreateDate.ToString(),
                        DelDate = msg.DelDate.HasValue? msg.DelDate.ToString():string.Empty
                    }).ToList();
                }

                return new List<MessageEntity>();
            }
        }
    }

    public enum MessageType
    {
        READ = 1,
        DELETE = 2
    }

    public class MessageTypeIndexes
    {
        public Array MessageTypeEnumArray
        {
            get
            {
                return Enum.GetValues(typeof(MessageType));
            }
        }

        public MessageType this[string msgType]
        {
            get
            {
                int messageType = int.Parse(msgType);
                return (MessageType)MessageTypeEnumArray.GetValue(--messageType);
            }
        }
    }

好了,都是些查詢,沒什麼可說的。this


OK,咱們如今就來看一下android的實現,咱們先看一下前臺佈局spa

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	android:scrollbars="vertical" android:fadingEdge="none">
	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="fill_parent" android:layout_height="fill_parent"
		android:orientation="vertical" android:background="@color/red1">
		<LinearLayout android:layout_height="wrap_content"
			android:layout_width="fill_parent" android:orientation="vertical"
			android:background="@color/teal1" android:layout_margin="1dp">
			<TableLayout android:layout_height="wrap_content"
				android:layout_width="wrap_content" android:shrinkColumns="1"
				android:stretchColumns="1" android:background="@color/teal"
				android:layout_margin="2dp">
				<TableRow>
					<TextView android:text="@string/labSendUser"
						android:textSize="8pt" android:gravity="right" android:textColor="@color/white">
					</TextView>
					<EditText android:id="@+id/txtSendUser"
						android:drawableLeft="@drawable/userhint" android:singleLine="true"
						android:maxLength="30" android:textSize="7pt"></EditText>
				</TableRow>
				<TableRow>
					<TextView android:text="@string/labTitle" android:gravity="right"
						android:textSize="8pt" android:layout_marginLeft="10pt"
						android:textColor="@color/white">
					</TextView>
					<EditText android:id="@+id/txtTitle" android:drawableLeft="@drawable/pencil"
						android:singleLine="true" android:maxLength="50"></EditText>
				</TableRow>
				<TableRow>
					<CheckBox android:id="@+id/chkIsDateCheck" android:text="@string/chkSendDate"
						android:textSize="8pt" android:gravity="center_vertical"
						android:layout_gravity="center_vertical" android:layout_span="2"></CheckBox>
				</TableRow>
				<TableRow>
					<TextView android:text="@string/chkBeginDate"
						android:textSize="8pt" android:textColor="@color/white"></TextView>
					<EditText android:id="@+id/txtStartDate"
						android:singleLine="true" android:editable="false"
						android:drawableRight="@drawable/calander"></EditText>
				</TableRow>
				<TableRow>
					<TextView android:text="@string/chkEndDate"
						android:textSize="8pt" android:textColor="@color/white"></TextView>
					<EditText android:id="@+id/txtEndDate" android:singleLine="true"
						android:editable="false" android:drawableRight="@drawable/calander"></EditText>
				</TableRow>
			</TableLayout>
			<LinearLayout android:orientation="horizontal"
				android:layout_width="fill_parent" android:layout_height="wrap_content">
				<ImageButton android:id="@+id/imgBtnSearch" android:src="@drawable/search"
					android:layout_weight="1" android:layout_width="wrap_content"
					android:layout_height="60dp" android:scaleType="centerInside"
					android:layout_marginLeft="5dp" android:layout_marginBottom="1dp"></ImageButton>
				<ImageButton android:id="@+id/imgBtnReset"
					android:layout_gravity="center_horizontal" android:layout_weight="1"
					android:src="@drawable/undo" android:layout_width="wrap_content"
					android:layout_height="60dp" android:scaleType="centerInside"
					android:layout_marginLeft="10dp" android:layout_marginRight="5dp"
					android:layout_marginBottom="1dp"></ImageButton>
			</LinearLayout>
		</LinearLayout>
		<TabHost android:id="@+id/tabhost" android:layout_width="fill_parent"
			android:layout_height="wrap_content">
			<LinearLayout android:orientation="vertical"
				android:layout_width="fill_parent" android:layout_height="fill_parent">
				<TabWidget android:id="@android:id/tabs"
					android:orientation="horizontal" android:layout_width="fill_parent"
					android:layout_height="wrap_content" />
				<FrameLayout android:id="@android:id/tabcontent"
					android:layout_width="fill_parent" android:layout_height="fill_parent">
					<HorizontalScrollView android:layout_height="fill_parent"
						android:layout_width="fill_parent"
						android:scrollbarAlwaysDrawHorizontalTrack="false">
						<TableLayout android:layout_width="fill_parent"
							android:layout_height="fill_parent"
							android:stretchColumns="0">
							<TableRow>
								<bruce.controls.CustomScrollViewer
									android:id="@+id/gvMessageInfo" 
									android:layout_width="fill_parent"
									android:layout_height="fill_parent">
								</bruce.controls.CustomScrollViewer>
							</TableRow>
						</TableLayout>
					</HorizontalScrollView>
				</FrameLayout>
			</LinearLayout>
		</TabHost>
	</LinearLayout>
</ScrollView>

仍是使用嵌套佈局,在最後咱們發現了一個tabHost,是的,這個就是來實現tab頁的。咱們看到tab頁中有一個一行一列的table,裏面放了一個bruce.controls.CustomScrollViewer。這個東西實際上是我從網上粘出來的一個用於顯示錶格的自定義控件,這個寫的裏面仍是有些問題,我對其進行了一些修改。3d


wKioL1OdFyXjXosjAAE_0A252kI921.jpg


今天主要不是針對這個,因此這個東西等下次我在講查看短消息功能的時候再說吧。

OK,咱們先看一下查詢條件,發送人和標題就不看了,時間查詢的話,若是勾選了,就必須選擇日期

private Boolean CheckSearchCriteria(String startDateStr, String endDateStr)
			throws ParseException {
		if (this.chkIsDateCheck.isChecked()) {
			if (startDateStr.length() == 0) {
				this.ShowToast("請選擇開始日期!");
				return false;
			}

			if (endDateStr.length() == 0) {
				this.ShowToast("請選擇開始日期!");
				return false;
			}

			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date startDate = dateFormat.parse(startDateStr + " 00:00:01");
			Date endDate = dateFormat.parse(endDateStr + " 23:59:59");

			if (startDate.after(endDate)) {
				this.ShowToast("開始日期不能大於結束日期!");
				return false;
			}
		}

		return true;
	}

之前咱們提示的時候都是使用Alert,如今的話,都是使用toast

private void ShowToast(String content) {
		Toast toast = Toast.makeText(getApplicationContext(), content,
				Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);

		LinearLayout toastContentView = (LinearLayout) toast.getView();
		ImageView imgToast = new ImageView(getApplicationContext());
		imgToast.setAdjustViewBounds(true);
		imgToast.setImageResource(R.drawable.alert);

		toastContentView.addView(imgToast, 0);
		toast.show();
	}

上次的時候咱們選擇日期是使用Click事件,此次咱們使用長按事件。

txtStartDate.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(android.view.View view) {
				if (chkIsDateCheck.isChecked()) {
					owner.ShowDatePicker(view);
				}
				return true;
			}
		});

		txtEndDate.setOnLongClickListener(new OnLongClickListener() {
			public boolean onLongClick(android.view.View view) {

				if (chkIsDateCheck.isChecked()) {
					owner.ShowDatePicker(view);
				}
				return true;
			}
		});

以下是ShowDatePicker的代碼,此次將這個方法寫成公用的。

	private void ShowDatePicker(final View view) {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog dialog = new DatePickerDialog(owner,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker dp, int year, int month,
							int dayOfMonth) {

						if (view instanceof EditText) {
							((EditText) view).setText(year + "-" + month + "-"
									+ dayOfMonth);
						}
					}
				}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));

		dialog.show();
	}

OK,以上是查詢部分,接下來咱們看一下查詢結果部分,先是構造tab頁。

private void InitTabHost() {
		tabHost = (TabHost) this.findViewById(R.id.tabhost);
		tabHost.setup();

		TabSpec specMessageNew = tabHost.newTabSpec("tabMessageNew");
		specMessageNew.setContent(R.id.gvMessageInfo);
		specMessageNew.setIndicator("已讀/未讀", this.getResources().getDrawable(
				R.drawable.emailread));

		TabSpec specMessageOld = tabHost.newTabSpec("tabMessageOld");
		specMessageOld.setContent(R.id.gvMessageInfo);

		specMessageOld.setIndicator("已刪消息", this.getResources().getDrawable(
				R.drawable.emaildel));

		tabHost.addTab(specMessageNew);
		tabHost.addTab(specMessageOld);
	}

在這裏,咱們加了兩個tab,setIndicator第一個參數是設置tab標題,第二個參數是設置tab圖標。

wKiom1OdGbrj4aFPAABUJr4ZXcM047.jpg

setContent是設置tab頁的內容,這裏咱們設置的是剛纔上面介紹的自定義控件。


好的,咱們最後看一下查詢部分,調用WebService代碼以下

private void SearchMessage() throws ParseException {

		String startDateStr = this.txtStartDate.getText().toString().trim();
		String endDateStr = this.txtEndDate.getText().toString().trim();

		if (!this.CheckSearchCriteria(startDateStr, endDateStr))
			return;

		String title = txtTitle.getText().toString().trim();
		String sendUser = txtSendUser.getText().toString().trim();

		if (this.chkIsDateCheck.isChecked()) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			startDateStr = startDateStr + " 00:00:01";
			endDateStr = endDateStr + " 23:59:59";
		}

		SoapObject response = this.GetMessageEntityList(title, sendUser,
				startDateStr, endDateStr, (String.valueOf(tabHost
						.getCurrentTab() + 1)));

		HashMap<String, Object> map = null;
		ArrayList<HashMap<String, Object>> mapList = new ArrayList<HashMap<String, Object>>();

		for (int i = 0; i < response.getPropertyCount(); i++) {
			SoapObject soapObj = (SoapObject) response.getProperty(i);

			map = new HashMap<String, Object>();
			map.put("Title", soapObj.getProperty("Title").toString());
			map.put("MessageContent", soapObj.getProperty("MessageContent")
					.toString());
			map.put("CreateUser", soapObj.getProperty("CreateUser").toString());
			map.put("CreateDate", soapObj.getProperty("CreateDate").toString());

			Object isReadObj = soapObj.getProperty("IsRead");
			Boolean isRead = Boolean.valueOf(isReadObj.toString());

			map.put("IsOpen", isRead ? R.drawable.folderopen
					: R.drawable.ckffolder);
			mapList.add(map);
		}

		this.BinData(mapList);
	}

在這裏咱們拿到了webservice返回的數據,調用代碼以下

final static String NAMESPACE = "http://tempuri.org/";
	final static String METHOD_NAME = "GetMessageEntity";
	final static String SOAP_ACTION = "http://tempuri.org/GetMessageEntity";
	final static String URL = main.baseIP + "/MessageMng.asmx?wsdl";
private SoapObject GetMessageEntityList(String title, String sendUser,
			String startDate, String endDate, String messageType) {
		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		PropertyInfo pi = new PropertyInfo();
		pi.setName("sendUser");
		pi.setType(String.class);
		pi.setValue(sendUser);
		request.addProperty(pi);

		pi = new PropertyInfo();
		pi.setName("receiveUser");
		pi.setType(String.class);
		pi.setValue(userNo);
		request.addProperty(pi);

		pi = new PropertyInfo();
		pi.setName("title");
		pi.setType(String.class);
		pi.setValue(title);
		request.addProperty(pi);

		pi = new PropertyInfo();
		pi.setName("messageType");
		pi.setType(String.class);
		pi.setValue(messageType);
		request.addProperty(pi);

		pi = new PropertyInfo();
		pi.setName("startDate");
		pi.setType(String.class);
		pi.setValue(startDate);
		request.addProperty(pi);

		pi = new PropertyInfo();
		pi.setName("endDate");
		pi.setType(String.class);
		pi.setValue(endDate);
		request.addProperty(pi);

		SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		soapEnvelope.dotNet = true;
		HttpTransportSE httpTS = new HttpTransportSE(URL);
		soapEnvelope.bodyOut = httpTS;
		soapEnvelope.setOutputSoapObject(request);// 設置請求參數
		// new MarshalDate().register(soapEnvelope);

		try {
			httpTS.call(SOAP_ACTION, soapEnvelope);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		SoapObject result = null;
		try {
			result = (SoapObject) soapEnvelope.getResponse();
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

OK,這些代碼都是之前講過的,在這裏就很少說了。咱們主要看BinData這個方法

private void BinData(ArrayList<HashMap<String, Object>> mapList) {
		String[] headers = new String[] {};

		if (mapList.size() > 0) {
			headers = mapList.get(0).keySet().toArray(headers);
		}
		
		gvMessage.setTableHeaders(this.TransferHeader(headers));
		gvMessage.setTableCellMaxEms(5);

		int[] imgColums = {1};
		gvMessage.setTableheadColor(R.color.teal);
		for (HashMap<String, Object> hm : mapList) {
			gvMessage.addNewRow(hm.values().toArray(), imgColums); 
		}
	}

第一步先拿出列頭,再轉成漢字

	private String[] TransferHeader(String[] headers) {
		String[] header=new String[]{};
		List<String> convertHeaderList = new ArrayList<String>();

		for (int i = 0; i < headers.length; i++) {
			if (headers[i] == "CreateUser") {
				convertHeaderList.add("發送人");
			}
			
			if (headers[i] == "Title") {
				convertHeaderList.add("標題");
			}

			if (headers[i] == "IsOpen") {
				convertHeaderList.add("已讀/未讀");
			}
			
			if (headers[i] == "CreateDate") {
				convertHeaderList.add("發送日期");
			}
			
			if (headers[i] == "MessageContent") {
				convertHeaderList.add("消息內容");
			}
		}
		
		return convertHeaderList.toArray(header);
	}

而後再循環設置行內容

for (HashMap<String, Object> hm : mapList) {
			gvMessage.addNewRow(hm.values().toArray(), imgColums); 
		}

這裏咱們循環ArrayList<HashMap<String,Object>>,而後往表格控件中加數據,第一個參數是內容,第二個參數是圖片內容所在的列的數組。OK,運行一下,查詢試試

wKioL1OdHD2Cpt3lAAHDlWWh3JM705.jpg

經過查詢check以後,咱們看看結果

wKiom1OdHWmg5-fFAAJHu4ZndZE618.jpg

還行吧,OK,今天就到這裏,下節我將給你們介紹這個自定義控件和實現

wKioL1OdHcTzbdOlAAF721w6y9M120.jpg

相關文章
相關標籤/搜索