Android ListView achieve simple filtering feature list

A simple screening function ListView

Screening principle: Get Spinner selected option and then the whole cycle is determined to be a list ListView delete option does not meet the column, re-screening of other options when it reacquired the initial lists for screening. (Own whim small way, may not be the best, but you are in the function can be achieved and the method is simple and easy to understand).

Renderings
Here Insert Picture Description

xml file (a Spinner and a ListView)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:padding="50dp"
    android:layout_height="match_parent">

    <Spinner
        android:entries="@array/saixuan"
        android:popupBackground="#00BCD4"
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </Spinner>

    <ListView
        android:id="@+id/lv4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

Java (listview used here is not to impress only provides filtering function block)

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
     @Override
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                data.clear();        //防止出现列表数据叠加的情况
                indatas();   //每次筛选前先重新获取一遍数据(方法里面是listview上传列表数据的代码)
                myAdapter.notifyDataSetChanged();        //列表更新
                String str=spinner.getSelectedItem().toString();   //获取所需要筛选出来的类型
                if (!str.equals("全部")){      // 全部 时不进行筛选
                    for (int a=0;a<data.size();a++){     //对列表每列都进行对比
                        if (!data.get(a).getTxv().equals(str)){   //当列表与选项不符合时
                            data.remove(a);      //移除当前列
                            a--;       //每次执行删除一个 size 都要减少 1 (因为列表中减少了一列)
                        }
                        myAdapter.notifyDataSetChanged();    //每次删除后更新列表
                    }
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });

Similarly this can be applied to a button click event, the code is basically exactly the same, the spinner's click event to replace the button click event!

Released six original articles · won praise 5 · Views 240

Guess you like

Origin blog.csdn.net/qq_44720366/article/details/103495894