在Android studio中我有一个书籍表和章节表,现在我要通过searchview来搜索某一本书中标题,并把结果显示在listview上
时间: 2024-05-07 10:21:53 浏览: 132
android带索引和标题的listview
5星 · 资源好评率100%
首先,你需要在布局文件中添加一个SearchView和ListView,如下所示:
```xml
<SearchView
android:id="@+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search by title" />
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
接着,在Activity中获取SearchView和ListView的实例,并设置SearchView的监听器来监听搜索操作。当用户输入搜索关键字并点击搜索按钮时,就会触发onQueryTextSubmit回调方法,在这个方法中执行查询操作,并将结果显示在ListView上。
```java
public class MainActivity extends AppCompatActivity {
private SearchView searchView;
private ListView listView;
private SQLiteDatabase db;
private BookListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取SearchView和ListView的实例
searchView = findViewById(R.id.search_view);
listView = findViewById(R.id.list_view);
// 打开或创建数据库
DatabaseHelper dbHelper = new DatabaseHelper(this);
db = dbHelper.getWritableDatabase();
// 设置SearchView的监听器
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// 执行查询操作
Cursor cursor = db.rawQuery("SELECT * FROM book WHERE title LIKE ?", new String[]{"%" + query + "%"});
adapter = new BookListAdapter(MainActivity.this, cursor);
listView.setAdapter(adapter);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
// Do nothing
return false;
}
});
}
}
```
最后,你需要实现一个自定义的Adapter来将查询结果显示在ListView上。这里我们假设你已经实现了一个BookListAdapter类来显示书籍的标题和作者。你只需要在onQueryTextSubmit回调方法中执行查询操作,并将结果传递给BookListAdapter即可。
```java
public class BookListAdapter extends CursorAdapter {
public BookListAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate the layout for each item of the ListView
return LayoutInflater.from(context).inflate(R.layout.book_list_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Retrieve data from the cursor and set it to the views
TextView titleTextView = view.findViewById(R.id.title_text_view);
TextView authorTextView = view.findViewById(R.id.author_text_view);
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String author = cursor.getString(cursor.getColumnIndexOrThrow("author"));
titleTextView.setText(title);
authorTextView.setText(author);
}
}
```
阅读全文