在自定义适配器实现过滤不执行列表视图搜索 [英] Implementing filterable in Custom Adapter does not perform search in Listview

查看:207
本文介绍了在自定义适配器实现过滤不执行列表视图搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个<一个延伸href=\"http://stackoverflow.com/questions/35763376/listview-search-not-working-in-popup-dialog/35763704?noredirect=1#comment59201305_35763704\">existing问题。我试图实现其自定义适配器列表视图搜索功能。根据我的最后一个问题的答案我已实施的可筛选在我的自定义适配器。

适配器code

 公共类CustomDialogAdapterBasic扩展ArrayAdapter&LT;串GT;实现可筛选{    上下文语境;
    清单&LT;串GT; values​​ComingIn =新的ArrayList&LT;串GT;();
    清单&LT;串GT; values​​Filtered =新的ArrayList&LT;串GT;();
    私人ItemFilter MFILTER =新ItemFilter();
    公共CustomDialogAdapterBasic(上下文的背景下,INT资源列表与LT;弦乐&GT; listComingIn){
        超(背景下,资源);
        this.context =背景;
        this.values​​ComingIn = listComingIn;
        this.values​​Filtered = listComingIn;
    }
    公共无效updateBrowser(){
        this.notifyDataSetChanged();
    }    @覆盖
    公众诠释的getCount(){
        返回values​​ComingIn.size();
    }    公共字符串的getItem(INT位置)抛出IndexOutOfBoundsException异常{
        返回values​​ComingIn.get(位置);
    }    众长getItemId(INT位置){
        返回的位置;
    }    @覆盖
    公共布尔isEnabled(INT位置){
        返回true;
    }    @覆盖
    公共查看getView(INT位置,查看convertView,父母的ViewGroup){
        LayoutInflater吹气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        查看rowView = inflater.inflate(R.layout.qustom_layout_list,父母,假);
        TextView中的TextView =(TextView中)rowView.findViewById(R.id.basic_text_view);        textView.setTypeface(TypeFaceController.generalTextFace(上下文));
        textView.setText(的getItem(位置));        返回rowView;
    }    公共过滤用getFilter(){
        返回MFILTER;
    }    私有类ItemFilter扩展过滤器{
        @覆盖
        保护FilterResults performFiltering(CharSequence的约束){            字符串filterString = constraint.toString()与toLowerCase()。
            Log.e(filterString,filterString);            FilterResults结果=新FilterResults();            最终名单&LT;串GT;名单= values​​ComingIn;            诠释计数=则为list.size();
            最终的ArrayList&LT;串GT; NLIST =新的ArrayList&LT;串GT;(计数);            串filterableString;            的for(int i = 0; I&LT;计数;我++){
                filterableString = list.get(ⅰ);
                如果(filterableString.toLowerCase()。包括(filterString)){
                    nlist.add(filterableString);
                }
            }            results.values​​ = NLIST;
            results.count = nlist.size();            返回结果;
        }        @燮pressWarnings(未登记)
        @覆盖
        保护无效publishResults(CharSequence的约束,FilterResults结果){
            values​​Filtered =(ArrayList的&LT;串GT;)results.values​​;
            notifyDataSetChanged();
        }    }}

显示列表视图弹出功能:

 私人无效showCollegePopUp(){
        QustomDialogBu​​ilder建设者=新QustomDialogBu​​ilder(EditYourProfile.this);
        builder.setDividerColor(ColorController.bright_green);        视图V = builder.setCustomView(R.layout.dialog_friend_layout,这一点);        最终的ListView列表=(ListView控件)v.findViewById(R.id.dialog_list_view_friends);
        LayoutInflater吹气=(LayoutInflater)EditYourProfile.this.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        footerView = inflater.inflate(R.layout.add_college_list_footer,列表,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(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                Toast.makeText(EditYourProfile.this,你好,Toast.LENGTH_LONG).show();
            }
        });
        footerView.setVisibility(View.GONE);        如果(listOfCollegeCourseNames.size()== 0){
            listOfCollegeCourseNames.add(抢学院......);
        }        适配器=新CustomDialogAdapterBasic(EditYourProfile.this,android.R.id.text1,listOfCollegeCourseNames);
        list.setPadding(16,0,0,0);
        list.setAdapter(适配器);
        inputSearch.addTextChangedListener(新TextWatcher(){            //对EditTex改变字的事件时
            @覆盖
            公共无效onTextChanged(CharSequence中,诠释开始,诠释之前,诠释计数){
                Log.e(文本,文本[+ S +]);                。adapter.getFilter()过滤(s.toString());
            }            @覆盖
            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数,
                                          INT后){            }            @覆盖
            公共无效afterTextChanged(编辑S){
            }        });
        builder.setTitle(选择你的大学);
        builder.setMessage(从列表中选择大学:);
        builder.setCancelable(真);        builder.setPositiveButton(取消,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface为arg0,ARG1 INT){            }
        });        list.setOnItemClickListener(新OnItemClickListener(){
            公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,INT位置,长的id){
                //随你的便,请                如果(adapter.getItem(位置)的ToString()。等于(collegeData.get(位置).getNameForCollege(​​))
                        || adapter.getItem(位置)的ToString()。等于(collegeData.get(位置).getStudentsNameForCollege(​​))){                    newCollegeName = adapter.getItem(位置)的ToString();                    collegeEditPage.setText(Html.fromHtml((newCollegeName))); // +
                                                                                //编辑));
                    //courseEditPage.setText(Html​​.fromHtml((\"Must选择新课程))); // +
                                                                                        //编辑));
                    //当然不存在了。
                    studentObject.setCourseName(NULL);
                    studentObject.setCollegeName(newCollegeName);                    如果(EditYourProfile.this.alertDialog!= NULL){
                        EditYourProfile.this.alertDialog.dismiss();
                        //刷新使用的列表。
                        listOfCollegeCourseNames =新的ArrayList&LT;串GT;();
                        newCollegeId = collegeData.get(位置).getCollegeUnqId();
                        studentObject.setCollegeId(newCollegeId);
                    }                }            }
        });        this.alertDialog = builder.create();
        this.alertDialog.setOnShowListener(新OnShowListener(){
            @覆盖
            公共无效昂秀(DialogInterface对话){
                AlertDialog alertDialog =(AlertDialog)对话框;
                Button按钮= alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                button.setTextSize(17);
                button.setTypeface(TypeFaceController.titleFace(getApplicationContext()));
            }
        });
        alertDialog.show();    }

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

 私人无效fetchAllCollegesAndDisplay(){
        最终名单&LT;&学院GT; collegeDetailList =新的ArrayList&LT;&学院GT;();
        ParseQuery&LT;&的parseObject GT;查询= ParseQuery.getQuery(大学);
        query.addAscendingOrder(名称);        query.findInBackground(新FindCallback&LT;&的parseObject GT;(){            @覆盖
            公共无效完成(列表&LT;&的parseObject GT;对象,com.parse.ParseException E){
                如果(E == NULL){
                    Log.e(对象大小,+ objects.size());
                        的for(int i = 0; I&LT; objects.size();我++){
                            如果(objects.get(I)获得(身份)!= NULL){
                                如果(objects.get(I).getBoolean(身份)==真){
                                    学院大学=新学院();
                                    college.setNameForCollege(​​objects.get(I)获得(名称)的toString());
                                    college.setCollegeUnqId(objects.get(ⅰ).getObjectId()); // 抓
                                    collegeDetailList.add(大专);
                                }                            }
                        }
                    generateList(collegeDetailList);                }            }        });
    }

填充列表功能:

 私人无效generateList(列表&LT;&GT; collegeOrCourseList){
        listOfCollegeCourseNames.remove(0);        如果(collegeOrCourseList.size()!= 0){            //检查列表类型的学院。
            如果(collegeOrCourseList.get(0)的instanceof学院){
                对于(对象C:collegeOrCourseList){                    如果(((学院)C).getStudentsNameForCollege(​​)!= NULL){
                        //listOfCollegeCourseNames.add(((College)C).getStudentsNameForCollege(​​));
                        listOfCollegeCourseNames.add(((学院)C).getNameForCollege(​​));
                    }其他                    如果(((学院)C).getNameForCollege(​​)!= NULL){
                        listOfCollegeCourseNames.add(((学院)C).getNameForCollege(​​));
                    }                    collegeData.add((学院)C);
                    adapter.notifyDataSetChanged();
                }
                footerView.setVisibility(View.VISIBLE);            }            如果(collegeOrCourseList.get(0)的instanceof课程){
                courseData.clear();
                对于(对象C:collegeOrCourseList){
                    listOfCollegeCourseNames.add(((课程)C).getCourse());
                    courseData.add((场),C);
                    adapter.notifyDataSetChanged();                }
            }        }
    }

Log.e(文本,文本[S +]); showCollegePopUp()工作,因为它应该我可以看到logcat中。

Log.e(filterString,filterString);

  CustomDialogAdapterBasic类也没有显示在日志中。但实际的过滤列表中没有显示出来。什么是错的code?


解决方案

的问题是,你把你的结果 values​​Filtered

  @覆盖
        保护无效publishResults(CharSequence的约束,FilterResults结果){
            values​​Filtered =(ArrayList的&LT;串GT;)results.values​​;
            notifyDataSetChanged();
        }

但你实际上并没有使用模型中的这些结果

  @覆盖
    公众诠释的getCount(){
        返回values​​ComingIn.size();
    }    公共字符串的getItem(INT位置)抛出IndexOutOfBoundsException异常{
        返回values​​ComingIn.get(位置);
    }

修改这些方法来

  @覆盖
    公众诠释的getCount(){
        返回values​​Filtered.size();
    }    公共字符串的getItem(INT位置)抛出IndexOutOfBoundsException异常{
        返回values​​Filtered.get(位置);
    }

This is an extension of an existing question. I am trying to implement search function in a listview having a custom adapter. According to my last question's answers I had implemented Filterable in my custom adapter.

The adapter code:

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

    }

}

The function to show the listview popup:

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

    }

The function to receive the data from the database:

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

                }

            }

        });
    }

The function to populate the list:

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

                }
            }

        }
    }

The Log.e("Text","Text [" + s +"]"); in showCollegePopUp() is working as it should I can see in logcat.

The Log.e("filterString", filterString); in

CustomDialogAdapterBasic class is also showing up in log. But the actual filtered list is not showing up. What is wrong with the code?

解决方案

The problem is that you are putting your results in valuesFiltered

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

but you are not actually using those results in your model

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

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

Change these methods to

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

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

这篇关于在自定义适配器实现过滤不执行列表视图搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆