編輯:關於Android編程
在前面的博客中,小編簡單的介紹了,點擊發現按鈕,自動加載熱門的相關數據,成長的腳步從不停歇,完成了發現的功能,今天我們來簡單看一下如何在搜索欄中輸入關鍵字,搜索出我們所需要的信息,今天這篇博文小編就簡單的介紹一下,如何輸入關鍵字,搜索出相應內容的故事。希望可以幫助到需要的小伙伴,還請小伙伴們多多指教。
首先,我們需要編寫實體裡面的代碼,這個功能小編用到了兩個實體,首先我們來看第一個實體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 ListContent; 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,具體代碼如下所示:
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(Map第三步,我們來編寫我們的xml布局,需要注意的是,我們搜索出來的信息是一個listview,所以在這裡我們需要布局兩個xml,第一個xml,search_content.xml具體代碼如下所示:params, 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; }
<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>
第二個search_result.xml代碼如下所示:
第四步,采用適配器adapter綁定數據,具體代碼如下所示:
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第五步,編寫java類裡面的代碼,如下所示: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; } }
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 ListlvSearchData = 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); } }; } }
最後,我們來看一下運行的效果,如下圖所示:
小編寄語:搜索的實現功能,小編就簡單的介紹到這裡,搜索實現了,但是小編到現在還是雲裡霧裡,不過沒關系,小編會越挫越勇的,這就是生命的意義,還是那句話對於小編來說,既是挑戰更是機遇,因為知識都是相通的,再者來說,在小編的程序人生中,留下最珍貴的記憶,雖然以後小編不一定從事安卓這個行業,代碼世界裡,很多種事,有的甜蜜,有的溫馨,有的婉轉成歌,有的綿延不息,在這些故事裡,我們唯一的共通之處就是,某年,某月,某個波瀾不驚的日子裡,曾經很愛很愛你!愛你--這段實習的日子裡,安卓帶給小編的種種的驚喜。在 下篇博文中小編將和小伙伴們一起來分享如何通過手機獲取驗證碼實現注冊的小功能,敬請期待`(*∩_∩*)′!
為了兼容簡體、繁體及其他語系,推薦使用UTF-8編碼。 首選,我們看看Android端應該怎麼做: 在發送前,應該對參數值要進行UTF-8編碼,我寫了一個s
網易新聞看起來很簡潔,左邊是一張圖片,右邊是一些文字信息,這樣的排版是十分常見的,給人的感覺就是簡潔明了,下面通過解析網絡json數據並展示到ListView上,來實現同
看下效果圖主要看下自定義view 代碼public class ProcessImageView extends ImageView{ private Context
一、線性布局