You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为带图片的ListView的自定义适配器添加搜索筛选功能

实现ListView搜索功能的完整修改方案

1. 自定义适配器修改(实现Filterable接口)

需要为适配器添加原始数据备份和过滤逻辑,修改后代码如下:

public class CustomAdapter extends BaseAdapter implements Filterable {
    // 过滤后展示的数据
    String [] result;
    String [] results;
    String [] resultss;
    int [] imageId;
    // 原始数据备份
    private String[] originalName;
    private String[] originalLiphoofolo;
    private String[] originalPhoofolo;
    private int[] originalImage;
    Context context;
    private static LayoutInflater inflater=null;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, String[] liphoofolo, String[] phoofolo, int[] prgmImages) {
        result=prgmNameList;
        results=liphoofolo;
        resultss=phoofolo;
        imageId=prgmImages;
        // 备份原始数据
        originalName = prgmNameList;
        originalLiphoofolo = liphoofolo;
        originalPhoofolo = phoofolo;
        originalImage = prgmImages;
        context=mainActivity;
        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return result.length;
    }
    @Override
    public Object getItem(int position) {
        return position;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    public static class Holder {
        TextView tv;
        TextView ts;
        TextView tss;
        ImageView img;
    }
    @SuppressLint({"ViewHolder", "InflateParams"})
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        Holder holder= new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.program_list, null);
        holder.tv= rowView.findViewById(R.id.textView1);
        holder.ts= rowView.findViewById(R.id.textView2);
        holder.tss= rowView.findViewById(R.id.textView3);
        holder.img= rowView.findViewById(R.id.imageView1);
        holder.tv.setText(result[position]);
        holder.ts.setText(results[position]);
        holder.tss.setText(resultss[position]);
        holder.img.setImageResource(imageId[position]);
        return rowView;
    }
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint == null || constraint.length() == 0) {
                    // 搜索内容为空时,展示原始数据
                    results.values = originalName;
                    results.count = originalName.length;
                    // 恢复原始数据源
                    result = originalName;
                    resultss = originalPhoofolo;
                    this.results = originalLiphoofolo;
                    imageId = originalImage;
                } else {
                    String searchStr = constraint.toString().toLowerCase();
                    // 临时存储匹配到的数据
                    List<String> matchName = new ArrayList<>();
                    List<String> matchLiphoofolo = new ArrayList<>();
                    List<String> matchPhoofolo = new ArrayList<>();
                    List<Integer> matchImage = new ArrayList<>();
                    for (int i = 0; i < originalName.length; i++) {
                        // 按名称匹配,可自行扩展匹配其他字段
                        if (originalName[i].toLowerCase().contains(searchStr)) {
                            matchName.add(originalName[i]);
                            matchLiphoofolo.add(originalLiphoofolo[i]);
                            matchPhoofolo.add(originalPhoofolo[i]);
                            matchImage.add(originalImage[i]);
                        }
                    }
                    results.values = matchName;
                    results.count = matchName.size();
                    // 更新过滤后的数据源
                    result = matchName.toArray(new String[0]);
                    resultss = matchPhoofolo.toArray(new String[0]);
                    this.results = matchLiphoofolo.toArray(new String[0]);
                    int[] imgArr = new int[matchImage.size()];
                    for (int i = 0; i < matchImage.size(); i++) {
                        imgArr[i] = matchImage.get(i);
                    }
                    imageId = imgArr;
                }
                return results;
            }
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                // 通知适配器数据变更刷新列表
                notifyDataSetChanged();
            }
        };
    }
}

2. 新增菜单配置文件

在res/menu目录下新建menu_main.xml,配置SearchView入口:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:title="搜索"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView" />
</menu>

3. 修改MainActivity代码

加载菜单并关联SearchView的搜索监听:

public class MainActivity extends AppCompatActivity {
    ListView lv;
    Context context;
    CustomAdapter customAdapter;
    public static int[] prgmImages = {
            R.drawable.ic_f
    };
    public static String[] prgmNameList = {
            "Bakoena"
    };
    public static String[] liphoofolo = {
            "Ba ana koena."
    };
    public static String[] phoofolo = {
            "Koena ke phoofolo e lulang metsing e phelang ka ho ja nama ea liphoofolo"
    };
    @SuppressLint("CutPasteId")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.drawable.ic_menu);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        context = this;
        lv = findViewById(R.id.listView);
        // 实例化适配器并保存实例
        customAdapter = new CustomAdapter(this, prgmNameList, liphoofolo, phoofolo, prgmImages);
        lv.setAdapter(customAdapter);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint("请输入搜索内容");
        // 设置搜索文本监听
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                // 输入内容变化时触发过滤
                customAdapter.getFilter().filter(newText);
                return true;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
}

内容的提问来源于stack exchange,提问作者Matete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 22:24:00