android:用自定义适配器在自定义列表视图中添加SearchView

3 人关注

我正在创建一个有3个标签片段的应用程序。这是其中一个片段,数据显示在列表视图中。我面临着在列表视图中添加搜索过滤器的麻烦。

我已经在这个片段中添加了搜索视图和列表,一切工作都没有任何错误,但是,当在搜索视图中输入时,列表没有排序,如果有人知道,请告诉我代码中的错误。

logcat消息,代码正在运行,但搜索视图不工作

W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f68b3d56a80, error=EGL_SUCCESS
V/RenderScript: 0x7f68b3d72000 Launching thread(s), CPUs 2
W/System: Ignoring header X-Parse-Client-Key because its value was null.
W/System: Ignoring header X-Parse-Client-Key because its value was null.
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f68b3e0f740, error=EGL_SUCCESS
W/System: Ignoring header X-Parse-Client-Key because its value was null.
D/score: Retrieved 23 _User
W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
I/Choreographer: Skipped 59 frames!  The application may be doing too much work on its main thread.
D/score: Retrieved 100 Organization
D/score: Retrieved 100 _User
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f68b3daa980, error=EGL_SUCCESS
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f68b3f336c0, error=EGL_SUCCESS
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f68b3daa300, error=EGL_SUCCESS
  

这是我的适配器java类。

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.parse.ParseObject;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class IndividualsAdaptor extends ArrayAdapter {
    protected Context mContext;
    protected List mStatus;
    public IndividualsAdaptor(Context context, int individuals, List status) {
        super(context, R.layout.t3, status);
        mContext = context;
        mStatus = status;
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (android.os.Build.VERSION.SDK_INT > 9)
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.t3, null);
            holder = new ViewHolder();
            holder.usernameHomepage = (TextView) convertView
                    .findViewById(R.id.fname);
            holder.statusHomepage = (TextView) convertView
                    .findViewById(R.id.lname);
            holder.pposition = (TextView) convertView
                    .findViewById(R.id.idposition);
            holder.orgName = (TextView) convertView
                    .findViewById(R.id.organizationname);
            holder.logo = (ImageView) convertView
                    .findViewById(R.id.imageView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        ParseObject statusObject = (ParseObject) mStatus.get(position);
        // title
        String username = statusObject.getString("firstname");
        holder.usernameHomepage.setText(username);
        // content
        String status = statusObject.getString("lastname");
        holder.statusHomepage.setText(status);
        // content
        String positions = statusObject.getString("position");
        holder.pposition.setText(positions);
        // content
        String org = statusObject.getString("organizationName");
        holder.orgName.setText(org);
        // logo
        URL url = null;
        Bitmap bmp = null;
        try {
            url = new URL("img hosting location" + statusObject.getString("image"));
            bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (MalformedURLException e) {
        }catch (IOException e) {
        holder.logo.setImageBitmap(bmp);
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class Individuals extends android.support.v4.app.ListFragment
        implements FindCallback<ParseObject> {
    private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
    SearchView sv;
    IndividualsAdaptor adaptor;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.individuals, container, false);
    @Override
    public void onViewCreated(View view, Bundle b) {
        super.onViewCreated(view, b);
        sv=(SearchView) view.findViewById(R.id.searchView1);
        final IndividualsAdaptor adaptor = new IndividualsAdaptor(getActivity(), mOrganization);
        setListAdapter(adaptor);
        ParseQuery.getQuery("_User").findInBackground(this);
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String text) {
                // TODO Auto-generated method stub
                return false;
            @Override
            public boolean onQueryTextChange(String text) {
                adaptor.getFilter().filter(text);
                return false;
    @Override
    public void done(List<ParseObject> scoreList, ParseException e) {
        if (e == null) {
            Log.d("score", "Retrieved " + scoreList.size() + " _User");
            mOrganization.clear();
            mOrganization.addAll(scoreList);
            ((IndividualsAdaptor) getListAdapter()).notifyDataSetChanged();
        } else {
            Log.d("score", "Error: " + e.getMessage());
  

list-view xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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"
    tools:context=".MainActivity" >
    <SearchView
    android:id="@+id/searchView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:queryHint="Search.."
</SearchView>
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/searchView1"
        android:layout_marginTop="22dp" >
    </ListView>
</RelativeLayout>
  

数据xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        android:layout_height="110dp"
        android:layout_width="110dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="14dp"
        android:layout_marginStart="14dp"
        android:layout_marginTop="19dp"
    <!--  img  -->
    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/organizationname"
        android:textSize="10sp"
        android:layout_below="@+id/idposition"
        android:layout_alignLeft="@+id/idposition"
        android:layout_alignStart="@+id/idposition"
        android:paddingTop="10px" />
    <TextView
        android:text="yyyyyyyyyyyyyyyyy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/idposition"
        android:textSize="10sp"
        android:layout_below="@+id/fname"
        android:layout_alignLeft="@+id/fname"
        android:layout_alignStart="@+id/fname" />
    <TextView
        android:id="@+id/fname"
        android:text="Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:layout_marginStart="12dp"
        android:textColor="#000"
        android:textSize="12sp"
        android:textStyle="bold"
        android:layout_alignTop="@+id/imageView"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView"
        android:layout_marginTop="13dp"
        android:fontFamily="sans-serif" />
    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/lname"
        android:textColor="#000"
        android:textSize="12sp"
        android:textStyle="bold"
        android:layout_above="@+id/idposition"
        android:layout_toRightOf="@+id/organizationname"
        android:layout_toEndOf="@+id/organizationname" />
</RelativeLayout>
    
4 个评论
对于SearchView,你需要 "setOnQueryTextListener "并调用适配器过滤器。我有一个关于ListView的博客。 programandroidlistview.blogspot.com 看一下简单适配器的例子,它显示了如何在文本变化时调用过滤器,数组适配器的例子显示了如何制作一个自定义的过滤器。希望这对你有帮助!
@I_A_Mok 嗨,我检查了你的博客并尝试了你的代码,你的适配器里有太多的代码,我在那里找不到搜索视图,你能为我的问题提供答案吗?
从你发布的代码来看,我认为你已经创建了SearchView,并且onQueryTextChange()似乎是有效的[你可以输入日志信息并检查]。因此,问题很可能是来自你的适配器,它可能需要一个自定义的过滤器。如果可能的话,请同时发布你的适配器和ParseObject类。
谢谢 @I_A_Mok ,我更新了适配器文件,我检查了添加日志信息,它说是空的,我无法找到错误。我试着给适配器添加一个过滤器,它抛出了更多的错误。.请检查,。
java
android
listview
android-searchmanager
android-filter
Faizal Munna
Faizal Munna
发布于 2017-02-05
3 个回答
i_A_mok
i_A_mok
发布于 2017-02-09
已采纳
0 人赞同

试试这个适配器代码。

public class IndividualsAdaptor extends ArrayAdapter {
protected Context mContext;
// Code for Custom Filter.
protected List mBackupList = new ArrayList();
public IndividualsAdaptor(Context context, List status) {
    super(context, R.layout.t3, status);
    mContext = context;
    // Code for Custom Filter.
    mBackupList.addAll(status);
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    if (convertView == null) {
        convertView = LayoutInflater.from(mContext).inflate(R.layout.t3, null);
        holder = new ViewHolder();
        holder.usernameHomepage = (TextView) convertView.findViewById(R.id.fname);
        holder.statusHomepage = (TextView) convertView.findViewById(R.id.lname);
        holder.pposition = (TextView) convertView.findViewById(R.id.idposition);
        holder.orgName = (TextView) convertView.findViewById(R.id.organizationname);
        holder.logo = (ImageView) convertView.findViewById(R.id.imageView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    ParseObject statusObject = (ParseObject) getItem(position);
    // title
    String username = statusObject.getString("firstname");
    holder.usernameHomepage.setText(username);
    // content
    String status = statusObject.getString("lastname");
    holder.statusHomepage.setText(status);
    // content
    String positions = statusObject.getString("position");
    holder.pposition.setText(positions);
    // content
    String org = statusObject.getString("organizationName");
    holder.orgName.setText(org);
    // logo
    URL url = null;
    Bitmap bmp = null;
    try {
        url = new URL("img hosting location" + statusObject.getString("image"));
        bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch (MalformedURLException e) {
    }catch (IOException e) {
    holder.logo.setImageBitmap(bmp);
    Picasso.with(mContext)
            .load(String.valueOf(url))
            .into(((ImageView) convertView
                    .findViewById(R.id.imageView)));
    return convertView;
public static class ViewHolder {
    TextView usernameHomepage;
    TextView statusHomepage;
    TextView orgName;
    TextView pposition;
    ImageView logo;
// Code for Custom Filter.
@Override
public Filter getFilter() {return new Filter(){
    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        String queryString = charSequence.toString().toLowerCase();
        List<ParseObject> filteredList = new ArrayList<>();
        ParseObject tmpItem;
        String tmpUsername, tmpStatus, tmpPositions, tmpOrg;
        for(int i=0; i<mBackupList.size(); i++){
            tmpItem = (ParseObject) mBackupList.get(i);
            tmpUsername = tmpItem.getString("firstname").toLowerCase();
            tmpStatus = tmpItem.getString("lastname").toLowerCase();
            tmpPositions = tmpItem.getString("position").toLowerCase();
            tmpOrg = tmpItem.getString("organizationName").toLowerCase();
            // The matching condition
            if(tmpUsername.contains(queryString)||tmpStatus.contains(queryString)||
                    tmpPositions.contains(queryString)||tmpOrg.contains(queryString)){
                filteredList.add(tmpItem);
        FilterResults filterResults = new FilterResults();
        filterResults.count = filteredList.size();
        filterResults.values = filteredList;
        return filterResults;
    @Override
    protected void publishResults(CharSequence charSequence, Filter.FilterResults filterResults) {
        clear();
        addAll((List<ParseObject>) filterResults.values);
public void updateBackupList(List newList){
    mBackupList.clear();
    mBackupList.addAll(newList);

和Individuals.java。

public class Individuals extends ListFragment {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
SearchView sv;
IndividualsAdaptor adaptor;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.individuals, container, false);
@Override
public void onViewCreated(View view, Bundle b) {
    super.onViewCreated(view, b);
    sv = (SearchView) view.findViewById(R.id.searchView1);
    adaptor = new IndividualsAdaptor(getActivity(), mOrganization);
    setListAdapter(adaptor);
    ParseQuery.getQuery("_User").findInBackground(this);
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String text) {
            return false;
        @Override
        public boolean onQueryTextChange(String text) {
            adaptor.getFilter().filter(text);
            return true;
@Override
public void done(List<ParseObject> scoreList, ParseException e) {
    if (e == null) {
        Log.d("score", "Retrieved " + scoreList.size() + " _User");
        mOrganization.clear();
        mOrganization.addAll(scoreList);
        ((IndividualsAdaptor) getListAdapter()).updateBackupList(mOrganization);
        ((IndividualsAdaptor) getListAdapter()).notifyDataSetChanged();
    } else {
        Log.d("score", "Error: " + e.getMessage());
    
嗨,谢谢,代码运行没有错误,但搜索仍然不工作。我张贴了问题中的日志猫信息,请检查@I_A_Mok
更新了答案!我没有注意到你的列表,mOrganization,一开始是空的,后来在后台更新了,现在在适配器里面创建了一个方法来更新备份列表。另一方面,请确保你更新正确的适配器代码文件。在你发布的代码中,适配器构造函数需要3个参数,但在片段中,只有2个参数。
好的,我忘了删除它,现在运行良好,谢谢你 :) @I_A_Mok
嗨 @I_A_Mok stackoverflow.com/questions/42968587/... 请检查您是否能
santosh kumar
santosh kumar
发布于 2017-02-09
0 人赞同

为视图创建一个类变量

  View view;
   @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view=inflater.inflate(R.layout.individuals, container, false);
            return view;

用这个进行搜索查看

 SearchView searchView = (SearchView)view.findViewById(R.id.searchTextView);

可以使用这种布局。

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:weightSum="1"
    android:layout_height="match_parent">
    <TextView android:id="@id/android:empty"
        android:text="No data"
        android:layout_width="match_parent"
        android:layout_weight="0.1"
        android:layout_height="0dp"
        tools:ignore="HardcodedText" />
    <SearchView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.1"
        android:id="@+id/searchUserTextField"
        android:background="@android:color/holo_red_dark"
        android:textColor="@android:color/white"
        android:textSize="14sp"
        android:hint="Search by Name or Company"
        android:textColorHint="#fff" />
    <ListView android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_weight="0.6"
        android:layout_height="wrap_content"
    <ImageView
        android:id="@+id/imageView7"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="0.2"
        android:src="@mipmap/ic_launcher"/>
</LinearLayout>
    
评论不用于扩展讨论;这次谈话已经 转到聊天室 .
Jins Lukose
Jins Lukose
发布于 2017-02-09
0 人赞同

i think problem is here: