android 搜索工具栏,Android记事本在菜单栏添加搜索按钮方法

效果图

16759614872ba50a3c519d548b1a21d6.png

9af3071c39f2e88544e6aacd39f66221.png

这个app结构和我之前将记事本开发的博客基本一致,我这里直接讲一下怎样添加

使用的开发软件为android studio

首先在res目录下新建文件夹menu,添加目录布局文件main_menu

778e3c0806c8fe455acc57eb1d146bfa.png

2a55008734d2969bfcc1849a05543fdc.png

之后在main_menu中添加如下代码

xmlns:app="http://schemas.android.com/apk/res-auto">

android:id="@+id/search"

android:icon="@drawable/ic_search_black_24dp"/这里设置图标,可以自由选择,我是在drawable下添加了放大镜的图标并在此引用

android:title="Search"

app:actionViewClass="android.widget.SearchView"

app:showAsAction="always"

>

之后在Mainactivity中重写onCreateOptionsMenu(Menu menu)函数,监听等功能都在此实现

public booleanonCreateOptionsMenu(Menu menu)

{

getMenuInflater().inflate(R.menu.main_menu,menu);

MenuItem search=menu.findItem(R.id.search);

SearchView mysearchview=(SearchView)search.getActionView();

mysearchview.setQueryHint("搜索");

mysearchview.setOnQueryTextListener(newSearchView.OnQueryTextListener(){

@Override

//当提交搜索框内容后执行的方法public booleanonQueryTextSubmit(String query) {return false;

}

@Override

//当搜索框内内容改变时执行的方法public booleanonQueryTextChange(String newText) {

refresh(newText);//数据更新函数,newText为获取到的搜索框中内容return false;

}

});return super.onCreateOptionsMenu(menu);

}

更新函数

voidrefresh(String key)

{

SimpleAdapter adapter= new SimpleAdapter(this,MainActivity.this.mytable.getdata(key), R.layout.list

,new String[]{"id","text","time"},new int[]{R.id.id,R.id.text,R.id.time});

ListView listView=(ListView)findViewById(R.id.vi);

listView.setAdapter(adapter);

}

这里附上数据库操作类中getdata()方法

public List>getdata(String key)

{List>list=new ArrayList>();

Map map=new HashMap();

String sql="SELECT id,text,time FROM "+TABLENAME+" WHERE text LIKE ‘%"+key+"%‘ OR time LIKE ‘%"+key+"%‘";

Cursor result=this.db.rawQuery(sql,null);for(result.moveToFirst();!result.isAfterLast();result.moveToNext())

{

map=new HashMap();

map.put("id",result.getInt(0));

map.put("text",result.getString(1));

map.put("time",result.getString(2));

list.add(map);

}return list;}

讲得比较笼统,具体的文件结构还请参照我之前的随笔https://www.cnblogs.com/liuleliu/p/12230819.html

原文:https://www.cnblogs.com/liuleliu/p/12256918.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值