編輯:關於 Android 程式設計
在前一篇文章中,我們完成了「點擊發現按鈕自動加載熱門數據」的功能。今天則要進一步挑戰搜索:如何在搜索欄輸入關鍵字,並把符合條件的內容以列表形式呈現出來。這篇筆記會把整個流程拆開講解,希望能幫到同樣在摸索的朋友。
整個功能可以拆成實體層、接口方法、XML 佈局、Adapter 綁定與 Activity 邏輯五個環節。首先來看實體類,這裡用到了兩個。
第一個實體 Content,代表單條段子內容:
package com.jczb.car.bean; import java.util.Date; import java.util.List; import android.R.integer; import android.R.integer; /** * 說明:段子內容實體 * 作者:丁國華 * 時間:2015-8-27下午2:32:57 */ @SuppressWarnings(serial) public class Content extends Entity { /** 內容表標識 */ private int uid; /** 顯示標題 */ private String title; /** 視頻或者圖片路徑 */ private String path; /**詳情*/ private String details; /**頻道類型*/ private String channelType; /**頻道名稱*/ private String channelName; /**作者*/ private String author; /**是否推薦*/ private String isRecommend; /**閱讀或者播放數量*/ private int browseNumber; /**評論數*/ private int commentbrowseNumber; /**贊數*/ private int praiseNumber; /**踩數*/ private int treadNumber; /**發布時間*/ private String issueTime; /**是否收藏*/ private int isCollect; /**關聯視頻*/ private List Content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getChannelType() { return channelType; } public void setChannelType(String channelType) { this.channelType = channelType; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getIsRecommend() { return isRecommend; } public void setIsRecommend(String isRecommend) { this.isRecommend = isRecommend; } public int getBrowseNumber() { return browseNumber; } public void setBrowseNumber(int browseNumber) { this.browseNumber = browseNumber; } public int getCommentbrowseNumber() { return commentbrowseNumber; } public void setCommentbrowseNumber(int commentbrowseNumber) { this.commentbrowseNumber = commentbrowseNumber; } public int getPraiseNumber() { return praiseNumber; } public void setPraiseNumber(int praiseNumber) { this.praiseNumber = praiseNumber; } public int getTreadNumber() { return treadNumber; } public void setTreadNumber(int treadNumber) { this.treadNumber = treadNumber; } public String getIssueTime() { return issueTime; } public void setIssueTime(String issueTime) { this.issueTime = issueTime; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } public int getIsCollect() { return isCollect; } public void setIsCollect(int isCollect) { this.isCollect = isCollect; } public List getContent() { return Content; } public void setContent(List content) { Content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } }
第二個實體 ContentVo,負責承接伺服器返回的 JSON 結果:
package com.jczb.car.bean; import java.util.List; /** * 說明:內容集合,用於Json串的解析 * 作者:丁國華 * 時間:2015-8-26下午9:45:26 */ @SuppressWarnings(serial) public class ContentVo extends Entity { public final static String CATALOG_ALL = all; public final static String CATALOG_NEWS = news; public final static String CATALOG_POST = post; public final static String CATALOG_SOFTWARE = software; public final static String CATALOG_CODE = code; /** 服務器返回結果:true或false */ private String result; /** 服務器返回的Json串解析為List結合 */ private List Content; public String getResult() { return result; } public void setResult(String result) { this.result = result; } public List getContent() { return Content; } public void setContent(List content) { Content = content; } }
接著編寫負責請求的接口方法,這裡同時處理了「有網路時取伺服器、無網路時讀本地快取」的邏輯:
/** * 說明:搜索內容 * * @param params * 當前頁碼(pagenow)和當前頁新聞數量(count)參數的集合 * @param isRefresh * 是否刷新 * @param contentVoId * 本地緩存id的組成部分 * @return * @user 丁國華 * @date 2015年9月11日 15:56:49 */ public ContentVo getSearchContentVoCategoryContent(Mapparams, boolean isRefresh, int contentVoId) throws AppException { ContentVo contentVo = null; // 構建緩存文件的key String key = searchCategoryContentVo_ + contentVoId; // 1.如果聯網則首先從服務器獲取數據 if (isNetworkConnected() &&(!isReadDataCache(key) || isRefresh)) { try { // 從服務器獲取contentVo的集合 contentVo = ApiClient.getSearchContent(this, params); // 如果能夠獲取到服務器中的數據則保存到本地緩存,只有保證數據不為空,且獲取到的結果為true的時候才緩存到本地 if (contentVo != null && contentVo.getResult().equals(false)) { contentVo.setCacheKey(key); saveObject(contentVo, key); } } catch (AppException e) { // 如果出現訪問中途斷網,則獲取本地緩存中的數據 contentVo = (ContentVo) readObject(key); // 如果本地緩存中數據為空,則拋出異常 if (contentVo == null) { throw e; } } } // 2.如果未聯網則從緩存中獲取數據 else { contentVo = (ContentVo) readObject(key); if (contentVo == null) { contentVo = new ContentVo(); } return contentVo; } return contentVo; }
第三步是佈局。搜索結果是一個 ListView,因此需要兩個 XML:一個承載搜索框(search_content.xml),一個作為列表項(search_result.xml)。
<framelayout android:background="@drawable/widget_head_bg" android:gravity="center_vertical" android:layout_height="30dip" android:layout_width="fill_parent" android:orientation="horizontal" android:paddingleft="5dip" android:paddingright="5dip"> </framelayout>
第四步,用自訂的 Adapter 把資料綁定到列表上。這裡透過 ViewHolder 模式快取控件引用,避免每次都重新 findViewById:
package com.jczb.car.adapter; import java.util.List; /** * 搜索資源Adapter類 * @author 丁國華 * @version 1.0 * @created 2015年9月9日 15:14:26 */ import com.jczb.car.R; import com.jczb.car.bean.Content; import com.jczb.car.bean.ContentVo; import com.jczb.car.bean.SearchContent; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class ListViewSearchAdapter extends BaseAdapter { private Context context; //運行上下文 private List listItems;//數據集合 private LayoutInflater listContainer; //視圖容器 private int itemViewResource;//自定義項視圖源 static class ListItemView{ //自定義控件集合 public TextView title; public ImageView isCollect; public TextView channelName; public TextView browseNumber; public TextView commentCount; } /** * 實例化Adapter * @param context * @param data * @param resource */ public ListViewSearchAdapter(Context context, List data,int resource) { this.context = context; this.listContainer = LayoutInflater.from(context); //創建視圖容器並設置上下文 this.itemViewResource = resource; this.listItems = data; } @Override public int getCount() { // TODO Auto-generated method stub return listItems.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub //Log.d(method, getView); //自定義視圖 ListItemView listItemView = null; if (convertView == null) { //獲取list_item布局文件的視圖 convertView = listContainer.inflate(this.itemViewResource, null); listItemView = new ListItemView(); //獲取控件對象 listItemView.title=(TextView)convertView.findViewById(R.id.search_result_news_title); listItemView.isCollect=(ImageView)convertView.findViewById(R.id.search_result_news_collecstar); listItemView.channelName=(TextView)convertView.findViewById(R.id.search_result_news_category); listItemView.browseNumber=(TextView)convertView.findViewById(R.id.search_result_news_playIcon); listItemView.commentCount=(TextView)convertView.findViewById(R.id.search_result_news_comment); //設置控件集到convertView convertView.setTag(listItemView); }else { listItemView = (ListItemView)convertView.getTag(); } //設置文字和圖片 Content searchContent= listItems.get(position); listItemView.title.setText(searchContent.getTitle()); listItemView.channelName.setText(searchContent.getChannelName()); listItemView.browseNumber.setText(searchContent.getBrowseNumber()+); listItemView.commentCount.setText(searchContent.getCommentbrowseNumber()+); return convertView; } }
第五步,撰寫 Activity 邏輯,包含搜索框監聽、進度條切換、Handler 更新列表與分頁加載等:
package com.jczb.car.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.jczb.car.AppContext; import com.jczb.car.AppException; import com.jczb.car.R; import com.jczb.car.adapter.ListViewNewsAdapter; import com.jczb.car.adapter.ListViewSearchAdapter; import com.jczb.car.bean.Content; import com.jczb.car.bean.ContentVo; import com.jczb.car.bean.Notice; import com.jczb.car.bean.SearchContent; import com.jczb.car.common.StringUtils; import com.jczb.car.common.UIHelper; import android.R.string; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class SearchContentActivity extends BaseActivity { /** 搜索按鈕 */ private Button btSearchPicture; /** 搜索的輸入框 */ private EditText etSearchFrame; /** 進度條 */ private ProgressBar mProgressbar; private ListView lvSearch; private View lvSearch_footer; private ListViewSearchAdapter lvSearchAdapter; private List lvSearchData = new ArrayList(); private TextView lvSearch_foot_more; private ProgressBar lvSearch_foot_progress; private Handler mSearchHandler; private int lvSumData; private String curSearchCatalog = ContentVo.CATALOG_SOFTWARE; private int curLvDataState; private String curSearchContent = ; private InputMethodManager imm; private final static int DATA_LOAD_ING = 0x001; private final static int DATA_LOAD_COMPLETE = 0x002; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_content); this.initView(); this.initData(); } /** * 頭部按鈕展示 * * @param type */ private void headButtonSwitch(int type) { switch (type) { case DATA_LOAD_ING: btSearchPicture.setClickable(false); mProgressbar.setVisibility(View.VISIBLE); break; case DATA_LOAD_COMPLETE: btSearchPicture.setClickable(true); mProgressbar.setVisibility(View.GONE); break; } } // 初始化視圖控件 private void initView() { imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); btSearchPicture = (Button) findViewById(R.id.search_content_btn); etSearchFrame = (EditText) findViewById(R.id.search_content_key); mProgressbar = (ProgressBar) findViewById(R.id.search_content_progress); btSearchPicture.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { etSearchFrame.clearFocus(); curSearchContent = etSearchFrame.getText().toString(); loadLvSearchData(curSearchCatalog, 0, mSearchHandler, UIHelper.LISTVIEW_ACTION_INIT); Toast.makeText(SearchContentActivity.this, shou, 1); } }); etSearchFrame .setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { imm.showSoftInput(v, 0); } else { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } }); etSearchFrame.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH) { if (v.getTag() == null) { v.setTag(1); etSearchFrame.clearFocus(); curSearchContent = etSearchFrame.getText().toString(); loadLvSearchData(curSearchCatalog, 0, mSearchHandler, UIHelper.LISTVIEW_ACTION_INIT); } else { v.setTag(null); } return true; } return false; } }); lvSearch_footer = getLayoutInflater().inflate(R.layout.listview_footer, null); lvSearch_foot_more = (TextView) lvSearch_footer .findViewById(R.id.listview_foot_more); lvSearch_foot_progress = (ProgressBar) lvSearch_footer .findViewById(R.id.listview_foot_progress); lvSearchAdapter = new ListViewSearchAdapter(this, lvSearchData, R.layout.search_result_item); lvSearch = (ListView) findViewById(R.id.search_content_listview); lvSearch.setVisibility(ListView.GONE); lvSearch.addFooterView(lvSearch_footer);// 添加底部視圖 必須在setAdapter前 lvSearch.setAdapter(lvSearchAdapter); lvSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { // 點擊底部欄無效 if (view == lvSearch_footer) return; SearchContent res = null; // 判斷是否是TextView if (view instanceof TextView) { res = (SearchContent) view.getTag(); } else { TextView title = (TextView) view .findViewById(R.id.search_result_news_title); res = (SearchContent) title.getTag(); } if (res == null) return; } }); } private void initData() { // TODO Auto-generated method stub mSearchHandler = new Handler() { public void handleMessage(Message msg) { headButtonSwitch(DATA_LOAD_COMPLETE); if (msg.what >= 0) { ContentVo list = (ContentVo) msg.obj; Notice notice = list.getNotice(); // 處理listview數據 switch (msg.arg1) { case UIHelper.LISTVIEW_ACTION_INIT: case UIHelper.LISTVIEW_ACTION_REFRESH: case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG: lvSumData = msg.what; lvSearchData.clear();// 先清除原有數據 lvSearchData.addAll(list.getContent()); break; case UIHelper.LISTVIEW_ACTION_SCROLL: lvSumData += msg.what; if (lvSearchData.size() > 0) { for (Content res1 : list.getContent()) { boolean b = false; for (Content res2 : lvSearchData) { if (res1.getId() == res2.getId()) { b = true; break; } } if (!b) lvSearchData.add(res1); } } else { lvSearchData.addAll(list.getContent()); } lvSearchData.addAll(list.getContent()); break; } if (msg.what < 20) { curLvDataState = UIHelper.LISTVIEW_DATA_FULL; lvSearchAdapter.notifyDataSetChanged(); lvSearch_foot_more.setText(R.string.load_full); } else if (msg.what == 20) { curLvDataState = UIHelper.LISTVIEW_DATA_MORE; lvSearchAdapter.notifyDataSetChanged(); lvSearch_foot_more.setText(R.string.load_more); } // 發送通知廣播 if (notice != null) { // UIHelper.sendBroadCast(SearchContentActivity.this, // notice); } } else if (msg.what == -1) { // 有異常--顯示加載出錯 & 彈出錯誤消息 curLvDataState = UIHelper.LISTVIEW_DATA_MORE; lvSearch_foot_more.setText(R.string.load_error); ((AppException) msg.obj) .makeToast(SearchContentActivity.this); } if (lvSearchData.size() == 0) { curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY; lvSearch_foot_more.setText(R.string.load_empty); } lvSearch_foot_progress.setVisibility(View.GONE); if (msg.arg1 != UIHelper.LISTVIEW_ACTION_SCROLL) { lvSearch.setSelection(0);// 返回頭部 } } }; } /** * 線程加載收藏數據 * * @param type * 0:全部收藏 1:軟件 2:話題 3:博客 4:新聞 5:代碼 * @param pageIndex * 當前頁數 * @param handler * 處理器 * @param action * 動作標識 */ private void loadLvSearchData(final String catalog, final int pageIndex, final Handler handler, final int action) { if (StringUtils.isEmpty(curSearchContent)) { UIHelper.ToastMessage(SearchContentActivity.this, 請輸入搜索內容); return; } headButtonSwitch(DATA_LOAD_ING); lvSearch.setVisibility(ListView.VISIBLE); new Thread() { public void run() { Message msg = new Message(); Map searchContentMap = new HashMap(); searchContentMap.put(keyword, curSearchContent); searchContentMap.put(pagenow, 1); searchContentMap.put(userId, 1); try { // 獲取全局對象Application AppContext appContext = (AppContext) getApplication(); /* 發現 */ ContentVo searchList = appContext.getSearchContentVoCategoryContent(searchContentMap, true, 4); msg.what = 5; msg.obj = searchList; } catch (AppException e) { e.printStackTrace(); msg.what = -1; msg.obj = e; } msg.arg1 = action;// 告知handler當前action if (curSearchCatalog.equals(catalog)) handler.sendMessage(msg); } }.start(); } private View.OnClickListener searchBtnClick(final Button btn, final String catalog) { return new View.OnClickListener() { public void onClick(View v) { btSearchPicture.setEnabled(true); // 開始搜索 etSearchFrame.clearFocus(); curSearchContent = etSearchFrame.getText().toString(); curSearchCatalog = catalog; loadLvSearchData(catalog, 0, mSearchHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG); } }; } }
最後來看看運行效果:

小結:以上就是搜索功能的完整實作思路。從實體建模、接口請求、佈局搭建、Adapter 綁定到 Activity 的事件與分頁處理,一步步串起來其實並不複雜,關鍵是理清資料在網路、快取與界面之間的流轉路徑。下一篇文章我們將分享如何透過手機驗證碼實現註冊功能,敬請期待。
跨平台行動 App 開發框架 iMAG 入門指南
iMAG 是一個相當輕巧的跨平台行動開發框架,寫一次即可同時支援 Android 與 iOS,只要有 Web 開發基礎就能快速上手。市面上跨平台方案不少,iMAG 的關鍵
ListView 入門四步走:從 ListActivity 到數據渲染
ListView 是 Android 最基礎的列表容器,理解它的第一步莫過於把數據「丟進去、跑出來」。整個流程拆成四步,非常適合當作首個練手範例。 Step 1:建立工程
安卓手機如何進入工程模式:一次搞懂隱藏測試入口
提到工程模式,很多非技術取向的使用者就頭痛。在一般人的印象裡,工程模式就是生硬的黑白畫面、整螢幕的英文和代碼指令,彷彿時光倒流回 DOS 時代,出於好奇想點進去,又怕一不
動手打造 Android 圖片三級緩存加載框架:原理與實作全解析
提到圖片加載的三級緩存,不少人第一反應就是「好難」。但其實只要靜下心來把流程拆開來看,親手寫上一兩遍,就會發現其中的邏輯相當清晰。本文就帶你從零梳理三級緩存的運作原理,並