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

如何修复Fragment内ListView关联EditText搜索功能的异常问题

问题原因排查

你代码里存在4个核心错误,是导致运行崩溃/功能不生效的原因:

  • 布局结构错误:你把搜索用的EditText放在了ListView的子项布局list_row2.xml中,但在Fragment主布局fragment_playbook.xml里没有该控件,运行时findViewById找EditText会直接抛出空指针异常
  • 变量重复声明:Fragment类中已经全局声明了arrayList2、listView2、playbookListAdapter,但在onCreateView中又重新定义了同名局部变量,导致全局变量未初始化,后续调用时也会触发空指针
  • 过滤逻辑失效:你直接调用ListView.setFilterText()过滤,默认的ArrayAdapter过滤规则是调用数据对象的toString()匹配,你没有重写PlaybookList的toString()方法,过滤不会生效
  • 点击索引错位:过滤后列表的显示顺序和原始arrayList2的索引不一致,直接用position取原始数组的元素会导致跳转的链接和选中项不匹配

修复步骤

1. 修改布局文件

(1)修改 fragment_playbook.xml(Fragment主布局,加入搜索栏)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Playbook">

    <!-- 搜索栏整体 -->
    <RelativeLayout
        android:id="@+id/searchBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/ic_baseline_search_24"
            android:id="@+id/searchImage" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_toRightOf="@id/searchImage"
            android:hint="输入关键词搜索"
            android:id="@+id/editTextFilter"/>
    </RelativeLayout>

    <ListView
        android:id="@+id/listView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/searchBar"/>

</androidx.constraintlayout.widget.ConstraintLayout>

(2)修改 list_row2.xml(列表子项布局,仅保留显示内容)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/termName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/TextAppearance.AppCompat.Title"
        android:text="Term"/>

</RelativeLayout>

2. 修改 PlaybookListAdapter 实现过滤功能

让Adapter实现Filterable接口,自定义过滤规则匹配TermName字段:

package com.example.gridiron;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

public class PlaybookListAdapter extends ArrayAdapter<PlaybookList> implements Filterable {

    private Context mContext;
    private int mResource;
    private List<PlaybookList> originalList; // 原始数据列表
    private List<PlaybookList> filteredList; // 过滤后的数据列表

    public PlaybookListAdapter(@NonNull Context context, int resource, @NonNull ArrayList<PlaybookList> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.mResource = resource;
        this.originalList = new ArrayList<>(objects);
        this.filteredList = objects;
    }

    @Override
    public int getCount() {
        return filteredList.size();
    }

    @Nullable
    @Override
    public PlaybookList getItem(int position) {
        return filteredList.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(mResource, parent, false);
        }

        TextView termName = convertView.findViewById(R.id.termName);
        termName.setText(getItem(position).getTermName());

        return convertView;
    }

    @NonNull
    @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 = originalList;
                    results.count = originalList.size();
                } else {
                    String filterPattern = constraint.toString().toLowerCase().trim();
                    List<PlaybookList> resultList = new ArrayList<>();
                    for (PlaybookList item : originalList) {
                        // 匹配术语名称
                        if (item.getTermName().toLowerCase().contains(filterPattern)) {
                            resultList.add(item);
                        }
                    }
                    results.values = resultList;
                    results.count = resultList.size();
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                filteredList = (List<PlaybookList>) results.values;
                notifyDataSetChanged();
            }
        };
    }
}

3. 修改 Playbook Fragment 代码

去掉重复变量声明,修改过滤和点击逻辑:

package com.example.gridiron;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import java.util.ArrayList;

public class Playbook extends Fragment {

    ArrayList<PlaybookList> arrayList2;
    ListView listView2;
    private PlaybookListAdapter playbookListAdapter;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public Playbook() {
        // Required empty public constructor
    }

    public static Playbook newInstance(String param1, String param2) {
        Playbook fragment = new Playbook();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_playbook, container, false);
        // 直接给全局变量赋值,不要重复声明
        listView2 = view.findViewById(R.id.listView2);
        EditText editTextFilter = view.findViewById(R.id.editTextFilter);

        arrayList2 = new ArrayList<>();
        arrayList2.add(new PlaybookList("Quarterback", "https://namu.wiki/w/%EC%BF%BC%ED%84%B0%EB%B0%B1"));
        arrayList2.add(new PlaybookList("Runningback", "https://namu.wiki/w/%EB%9F%AC%EB%8B%9D%EB%B0%B1"));

        playbookListAdapter = new PlaybookListAdapter(getActivity(), R.layout.list_row2, arrayList2);
        listView2.setAdapter(playbookListAdapter);

        // 修改过滤逻辑,调用Adapter的filter
        editTextFilter.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) {
                playbookListAdapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        // 修改点击逻辑,从Adapter拿当前选中的项,避免索引错位
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PlaybookList selectedItem = playbookListAdapter.getItem(position);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(selectedItem.getTermURL()));
                startActivity(intent);
            }
        });

        return view;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:45:07