搜索----Android Demo

来源:互联网 发布:大数据获取方式 编辑:程序博客网 时间:2024/05/19 17:11

       在前面的博客中,小编简单的介绍了,点击发现按钮,自动加载热门的相关数据,成长的脚步从不停歇,完成了发现的功能,今天我们来简单看一下如何在搜索栏中输入关键字,搜索出我们所需要的信息,今天这篇博文小编就简单的介绍一下,如何输入关键字,搜索出相应内容的故事。希望可以帮助到需要的小伙伴,还请小伙伴们多多指教。

       首先,我们需要编写实体里面的代码,这个功能小编用到了两个实体,首先我们来看第一个实体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<VideoRelation> 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<VideoRelation> getContent() {return Content;}public void setContent(List<VideoRelation> 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> Content;public String getResult() {return result;}public void setResult(String result) {this.result = result;}public List<Content> getContent() {return Content;}public void setContent(List<Content> 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<String, Object> params,boolean isRefresh, int contentVoId) throws AppException {ContentVo contentVo = null;// 构建缓存文件的keyString 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;}
        第三步,我们来编写我们的xml布局,需要注意的是,我们搜索出来的信息是一个listview,所以在这里我们需要布局两个xml,第一个xml,search_content.xml具体代码如下所示:

<?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:orientation="vertical"  android:background="@color/white"><FrameLayout   android:layout_width="fill_parent"   android:layout_height="30dip"   android:gravity="center_vertical"   android:paddingLeft="5dip"   android:paddingRight="5dip"   android:orientation="horizontal"   android:background="@drawable/widget_head_bg"><EditText        android:id="@+id/search_content_key"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_gravity="left|center"        android:layout_marginRight="36dip"        android:singleLine="true"        android:focusable="true"         android:focusableInTouchMode="true"        android:imeOptions="actionSearch"        android:background="@drawable/edit_search_bg"        android:hint="输入搜索内容"/>  <Button    android:id="@+id/search_content_btn"android:layout_width="wrap_content"       android:layout_height="30dip"       android:layout_gravity="right|center"      android:background="@drawable/btn_search_bg"/>     <ProgressBar android:id="@+id/search_content_progress" style="@style/loading_small"android:layout_gravity="right|center"android:layout_marginRight="8dip"android:background="@color/white"android:visibility="gone"/></FrameLayout><LinearLayout       android:id="@+id/search_ll"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent">   <ListView  android:id="@+id/search_content_listview"   style="@style/widget_listview"/></LinearLayout>   </LinearLayout>


        第二个search_result.xml代码如下所示:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="2dp">        <TextView            android:id="@+id/search_result_news_title"            style="@style/list_notify_view"            android:layout_width="wrap_content"            android:layout_height="fill_parent"            android:layout_marginLeft="4dp"            android:layout_weight="10"            android:background="@null"            android:ellipsize="end"            android:singleLine="true"            android:textSize="16sp"/>        <!-- 收藏按钮 -->        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:layout_marginRight="5dp"            android:layout_weight="0.5"            android:gravity="center" >         <ImageView                android:id="@+id/search_result_news_collecstar"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1.5"                android:src="@drawable/my_collect_usercenter" />            <TextView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_weight="1"                android:gravity="center_vertical|center"                android:text="@string/home_news_love"                android:textColor="@color/home_news_text_color" />        </LinearLayout>    </LinearLayout>    <ImageView        android:id="@+id/search_result_picture_id"        android:layout_width="match_parent"        android:layout_height="150dp"        android:layout_margin="5dp"        android:scaleType="centerCrop"        android:src="@drawable/cheduanzi_tuwen" />    <!-- 视频底部有关信息 -->    <LinearLayout        android:layout_width="match_parent"        android:layout_height="26dp"        android:layout_marginTop="2dp" >        <!-- 视频所属频道 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_marginLeft="4dp"            android:layout_weight="1" >            <TextView                android:id="@+id/search_result_news_category"                style="@style/list_notify_view"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/home_categorybg"                android:gravity="center_vertical|center" />        </LinearLayout>        <!-- 视频播放次数 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="0.5" >            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_marginLeft="0dp"                android:src="@drawable/news_playicon" />            <TextView                android:id="@+id/search_result_news_playIcon"                style="@style/list_notify_view"                android:layout_width="wrap_content"                android:layout_height="fill_parent"                android:layout_marginLeft="2dp"                android:background="@null"                android:gravity="center_vertical" />        </LinearLayout>        <!-- 视频相关评论 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="0.4" >            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_marginLeft="0dp"                android:src="@drawable/news_comment" />            <TextView                android:id="@+id/search_result_news_comment"                style="@style/list_notify_view"                android:layout_width="wrap_content"                android:layout_height="fill_parent"                android:layout_marginLeft="2dp"                android:background="@null"                android:gravity="center_vertical" />        </LinearLayout>        <!-- 转载视频 -->        <LinearLayout            android:layout_width="0dp"            android:layout_height="fill_parent"            android:layout_weight="0.3"            android:gravity="center_vertical|center" >            <ImageView                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_marginLeft="0dp"                android:src="@drawable/share_cheduanzi" />        </LinearLayout>    </LinearLayout>    <View        android:layout_width="fill_parent"        android:layout_height="5.0dip"        android:layout_marginTop="2dp"        android:background="@color/home_news_divider_color" /></LinearLayout>
        第四步,采用适配器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<Content> 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<Content> data,int resource) {this.context = context;this.listContainer = LayoutInflater.from(context);//创建视图容器并设置上下文this.itemViewResource = resource;this.listItems = data;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn listItems.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn 0;}@Overridepublic 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);//设置控件集到convertViewconvertView.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;}}
        第五步,编写java类里面的代码,如下所示:

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<Content> lvSearchData = new ArrayList<Content>();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;// 判断是否是TextViewif (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 stubmSearchHandler = 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<String, Object> searchContentMap = new HashMap<String, Object>();searchContentMap.put("keyword", curSearchContent);searchContentMap.put("pagenow", "1");searchContentMap.put("userId", "1");try {// 获取全局对象ApplicationAppContext 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当前actionif (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);}};}}

       最后,我们来看一下运行的效果,如下图所示:

        

        小编寄语:搜索的实现功能,小编就简单的介绍到这里,搜索实现了,但是小编到现在还是云里雾里,不过没关系,小编会越挫越勇的,这就是生命的意义,还是那句话对于小编来说,既是挑战更是机遇,因为知识都是相通的,再者来说,在小编的程序人生中,留下最珍贵的记忆,虽然以后小编不一定从事安卓这个行业,代码世界里,很多种事,有的甜蜜,有的温馨,有的婉转成歌,有的绵延不息,在这些故事里,我们唯一的共通之处就是,某年,某月,某个波澜不惊的日子里,曾经很爱很爱你!爱你--这段实习的日子里,安卓带给小编的种种的惊喜。在 下篇博文中小编将和小伙伴们一起来分享如何通过手机获取验证码实现注册的小功能,敬请期待`(*∩_∩*)′!

3 0
原创粉丝点击