android : adding SearchView inside a ListView with Custom Adaptor

耗尽温柔 提交于 2019-12-05 20:14:48

Try this adapter code:

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);
}
}

And 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());
    }
}
}

create a class variable for view

  View view;

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

use this for search view

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

This layout can be used.

    <?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>

i think problem is here:

SearchView searchView = (SearchView)view.findViewById(R.id.searchTextView);
    view=inflater.inflate(R.layout.individuals, container, false);

you are calling searchview before view created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!