在自定义适配器中实现可过滤功能不会在Listview

时间:2016-03-03 07:56:11

标签: android listview search

这是existing question的扩展。我试图在具有自定义适配器的列表视图中实现搜索功能。根据我上一个问题的答案,我在自定义适配器中实现了可过滤

适配器代码

public class CustomDialogAdapterBasic extends ArrayAdapter<String> implements Filterable {

    Context context;
    List<String> valuesComingIn = new ArrayList<String>();
    List<String> valuesFiltered = new ArrayList<String>();
    private ItemFilter mFilter = new ItemFilter();


    public CustomDialogAdapterBasic(Context context, int resource, List<String> listComingIn) {
        super(context, resource);
        this.context = context;
        this.valuesComingIn = listComingIn;
        this.valuesFiltered = listComingIn;
    }


    public void updateBrowser() {
        this.notifyDataSetChanged();
    }

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

    public String getItem(int position) throws IndexOutOfBoundsException {
        return valuesComingIn.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean isEnabled(int position) {
        return true;
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.qustom_layout_list, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.basic_text_view);

        textView.setTypeface(TypeFaceController.generalTextFace(context));
        textView.setText(getItem(position));

        return rowView;
    }

    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();
            Log.e("filterString", filterString);

            FilterResults results = new FilterResults();

            final List<String> list = valuesComingIn;

            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            valuesFiltered = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }

}

显示listview弹出窗口的功能:

private void showCollegePopUp(){
        QustomDialogBuilder builder = new QustomDialogBuilder(EditYourProfile.this);
        builder.setDividerColor(ColorController.bright_green);

        View v = builder.setCustomView(R.layout.dialog_friend_layout, this);

        final ListView list = (ListView) v.findViewById(R.id.dialog_list_view_friends);
        LayoutInflater inflater = (LayoutInflater)EditYourProfile.this.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        footerView = inflater.inflate(R.layout.add_college_list_footer, list, false);
        list.addFooterView(footerView);


        inputSearch = (EditText)v.findViewById(R.id.inputSearch);
        TextView textView = (TextView) v.findViewById(R.id.add_college);

        textView.setTypeface(TypeFaceController.generalTextFace(EditYourProfile.this));

        LinearLayout footer_linear_layout = (LinearLayout)v.findViewById(R.id.footer_linear_layout);
        footer_linear_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(EditYourProfile.this, "hello", Toast.LENGTH_LONG).show();
            }
        });
        footerView.setVisibility(View.GONE);

        if (listOfCollegeCourseNames.size() == 0) {
            listOfCollegeCourseNames.add("Grabbing colleges...");
        }

        adapter = new CustomDialogAdapterBasic(EditYourProfile.this, android.R.id.text1, listOfCollegeCourseNames);
        list.setPadding(16, 0, 0, 0);
        list.setAdapter(adapter);
        inputSearch.addTextChangedListener(new TextWatcher() {

            //Event when changed word on EditTex
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e("Text","Text [" + s +"]");

                adapter.getFilter().filter(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }

        });
        builder.setTitle("Select your college");
        builder.setMessage("Choose College from the list:");
        builder.setCancelable(true);

        builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1){

            }
        });

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                // Do as you please

                if (adapter.getItem(position).toString().equals(collegeData.get(position).getNameForCollege())
                        || adapter.getItem(position).toString().equals(collegeData.get(position).getStudentsNameForCollege())) {

                    newCollegeName = adapter.getItem(position).toString();

                    collegeEditPage.setText(Html.fromHtml((newCollegeName)));// +
                                                                                // edit));
                    //courseEditPage.setText(Html.fromHtml(("Must choose new course")));// +
                                                                                        // edit));
                    // course doesn't exist anymore.
                    studentObject.setCourseName(null);
                    studentObject.setCollegeName(newCollegeName);

                    if (EditYourProfile.this.alertDialog != null) {
                        EditYourProfile.this.alertDialog.dismiss();
                        // Refresh the list used.
                        listOfCollegeCourseNames = new ArrayList<String>();
                        newCollegeId = collegeData.get(position).getCollegeUnqId();
                        studentObject.setCollegeId(newCollegeId);
                    }

                }

            }
        });

        this.alertDialog = builder.create();
        this.alertDialog.setOnShowListener(new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog){
                AlertDialog alertDialog = (AlertDialog) dialog;
                Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                button.setTextSize(17);
                button.setTypeface(TypeFaceController.titleFace(getApplicationContext()));
            }
        });
        alertDialog.show();

    }

从数据库接收数据的功能:

private void fetchAllCollegesAndDisplay(){
        final List<College> collegeDetailList = new ArrayList<College>();
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Colleges");
        query.addAscendingOrder("name");

        query.findInBackground(new FindCallback<ParseObject>() {

            @Override
            public void done(List<ParseObject> objects, com.parse.ParseException e){
                if (e == null) {
                    Log.e("Objects size", "" + objects.size());
                        for (int i = 0; i < objects.size(); i++) {
                            if (objects.get(i).get("status") != null) {
                                if (objects.get(i).getBoolean("status") == true){
                                    College college = new College();
                                    college.setNameForCollege(objects.get(i).get("name").toString());
                                    college.setCollegeUnqId(objects.get(i).getObjectId()); // Grab
                                    collegeDetailList.add(college);
                                }

                            }
                        }
                    generateList(collegeDetailList);

                }

            }

        });
    }

填充列表的功能:

private void generateList(List<?> collegeOrCourseList){
        listOfCollegeCourseNames.remove(0);

        if (collegeOrCourseList.size() != 0) {

            // Check if the list is of type College.
            if (collegeOrCourseList.get(0) instanceof College) {
                for (Object c : collegeOrCourseList) {

                    if (((College) c).getStudentsNameForCollege() != null) {
                        //listOfCollegeCourseNames.add(((College) c).getStudentsNameForCollege());
                        listOfCollegeCourseNames.add(((College) c ).getNameForCollege());
                    } else

                    if (((College) c).getNameForCollege() != null) {
                        listOfCollegeCourseNames.add(((College) c).getNameForCollege());
                    }

                    collegeData.add((College) c);
                    adapter.notifyDataSetChanged();


                }
                footerView.setVisibility(View.VISIBLE);

            }

            if (collegeOrCourseList.get(0) instanceof Course) {
                courseData.clear();
                for (Object c : collegeOrCourseList) {
                    listOfCollegeCourseNames.add(((Course) c).getCourse());
                    courseData.add((Course) c);
                    adapter.notifyDataSetChanged();

                }
            }

        }
    }

Log.e("Text","Text [" + s +"]");中的showCollegePopUp()正在运行,因为我应该在logcat中看到它。

中的Log.e("filterString", filterString);
CustomDialogAdapterBasic class is also showing up in log. But the actual filtered list is not showing up. What is wrong with the code?

1 个答案:

答案 0 :(得分:1)

问题是您将结果放在valuesFiltered

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            valuesFiltered = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

但您实际上并未在模型中使用这些结果

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

    public String getItem(int position) throws IndexOutOfBoundsException {
        return valuesComingIn.get(position);
    }

将这些方法更改为

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

    public String getItem(int position) throws IndexOutOfBoundsException {
        return valuesFiltered.get(position);
    }