布局文件:
<?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:background="@color/colorGray"
android:orientation="vertical"
>
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
主程序文件
package com.toby.personal.testlistview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.SearchView;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
final private static String TAG = "Toby_Test";
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] mString = {"test aaa", "test bbb", "test ccc"};
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mString));
listView.setTextFilterEnabled(true);
listView.setVisibility(View.GONE);
final SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.setIconifiedByDefault(false); // 是否缩小为图标
searchView.setOnQueryTextListener(this); // 注册事件监听器
searchView.setSubmitButtonEnabled(true); // 显示搜索按钮
searchView.setQueryHint("Find"); // 默认显示的提示文本
}
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(this, R.string.show, Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
listView.setVisibility(View.GONE);
listView.clearTextFilter(); // 清除 ListView 的过滤
} else {
listView.setFilterText(newText); // 使用用户输入的内容对 ListView 列表项进行过滤
listView.setVisibility(View.VISIBLE);
}
return true;
}
}
测试程序的运行效果:
显示效果参考文献:《疯狂Android讲义(第2版)》
网友评论