(注: 教程使用的是android studio作为开发工具)
新建一个项目,选择Basic Activity:
content_main.xml布局代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/content_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.apizl.searchlistview.MainActivity" tools:showIn="@layout/activity_main"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPersonName" android:text="" android:hint="输入搜索内容" android:id="@+id/editText" /> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/my_list" android:layout_below="@+id/editText"/> </RelativeLayout>
放一个EditText作为搜索框,id命名为editText;然后下面放一个ListView,id为my_list;
再新建一个布局文件,作为listview的item布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="50dp" app:layout_collapseParallaxMultiplier="0.0" android:layout_gravity="center" android:padding="5dp"> <TextView android:text="TextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/item" /> </LinearLayout>
放一个TextView,然后id就叫item;
主要代码:
public class MainActivity extends AppCompatActivity { private ListView listView; private ArrayAdapter arrayAdapter; private EditText searchBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Listview 搜索"); setSupportActionBar(toolbar); searchBox = (EditText) findViewById(R.id.editText); //搜索框 listView = (ListView) findViewById(R.id.my_list); //listview布局 //适配器 arrayAdapter = new ArrayAdapter(this, R.layout.list_item,R.id.item, new Object[]{"Hello World", "Hello Java", "Hello android", "Hello", "1234", "哈哈哈哈"}); //设置适配器 listView.setAdapter(arrayAdapter); //edittext的内容变更监视 searchBox.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { arrayAdapter.getFilter().filter(s); //一行代码实现搜索效果 } @Override public void afterTextChanged(Editable s) { } }); } }
效果图:
关键字词: