1.先来看一下效果吧:
还有
2.实现贼简单,看代码
MainActivity:
public class MainActivity extends AppCompatActivity {
private SearchView searchView;
private RecyclerView recy;
private ArrayList findList=new ArrayList<>();
private ArrayList list=new ArrayList<>();
private listViewAdapter findAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initData() {
list.add("我是程序员");
list.add("我是程序员哈哈哈");
list.add("我是人");
list.add("我不是人");
list.add("lalla ");
list.add("Ia");
list.add("Ja");
list.add("Ka");
list.add("La");
list.add("Ma");
list.add("Na");
}
private void initView() {
searchView = (SearchView) findViewById(R.id.searchEdit);
recy = (RecyclerView) findViewById(R.id.Recy);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//输入完成后,提交时触发的方法,一般情况是点击输入法中的搜索按钮才会触发,表示现在正式提交了
public boolean onQueryTextSubmit(String query) {
if(TextUtils.isEmpty(query)) {
Toast.makeText(MainActivity.this, "请输入查找内容!", Toast.LENGTH_SHORT).show();
recy.setAdapter(findAdapter);
}else{
findList.clear();
for(int i = 0; i < list.size(); i++) {
// iconInformation information = list.get(i);
String s = list.get(i);
if(s.equals(query)) {
findList.add(s);
break;
}
}
if(findList.size() == 0) {
Toast.makeText(MainActivity.this, "查找的商品不在列表中", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "查找成功", Toast.LENGTH_SHORT).show();
findAdapter = new listViewAdapter(findList);
recy.setAdapter(findAdapter);
}
}
return true;
}
//在输入时触发的方法,当字符真正显示到searchView中才触发,像是拼音,在输入法组词的时候不会触发
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)) {
recy.setAdapter(findAdapter);
}
else {
findList.clear();
for(int i = 0; i < list.size(); i++) {
// iconInformation information = list.get(i);
String s = list.get(i);
if(s.contains(newText)) {
findList.add(s);
}
}
recy.setLayoutManager(new LinearLayoutManager(MainActivity.this));
findAdapter = new listViewAdapter(findList);
findAdapter.notifyDataSetChanged();
recy.setAdapter(findAdapter);
}
return true;
}
});
}
}
适配器 :
public class listViewAdapter extends RecyclerView.Adapter{
ArrayList mArray;
private View inflate;
public listViewAdapter(ArrayList mArray) {
this.mArray = mArray;
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.recytext, parent, false);
Holder holder = new Holder(inflate);
return holder;
}
@Override
public void onBindViewHolder(Holder holder, final int position) {
holder.name.setText(mArray.get(position));
}
@Override
public int getItemCount() {
return mArray.size();
}
public class Holder extends RecyclerView.ViewHolder {
private final TextView name;
public Holder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
}
}
}
main_xml布局:
适配器中引用的布局:
由此可见就是这么简单,数据可以进行网络请求添加数据,也可以添加自己的死数据,看需求,
这次就分享到这了 !!!