其实我写代码最担心遇到关于适配器的使用,在我的感觉中适配器是个难度很大的知识点,但是不能因为难而不去学习啊,毕竟现在时间很充裕,可以慢慢学,所以,不会也要写,真所谓,迎难而上啊。 下面是SearchView与ListView相结合的简单使用。
布局文件main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<SearchView
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="搜索联系人"
tools:ignore="NewApi" />
<ListView
android:id="@+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Main.java
package com.example.androidtest1;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnQueryTextListener{
private SearchView search;
private ListView lv;
private String[] names=new String[]{"张三","张强","李四","李珊"};
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initview();
}
@SuppressLint("NewApi")
public void initview()
{
search =(SearchView)findViewById(R.id.search);
search.setOnQueryTextListener(this);
lv=(ListView)findViewById(R.id.lv);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);//这个属性为true表示listview获得当前焦点的时候,相应用户输入的匹配符,筛选出匹配的
}
@Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
if(arg0.length()!=0){
lv.setFilterText(arg0);
}else{
lv.clearTextFilter();
}
return false;
}
@Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
}