getFilter()不会过滤listview

时间:2014-01-26 17:52:18

标签: android android-listview

我已尝试使用下面给出的代码在我的应用中使用自定义BaseAdapter实现搜索功能。我使用edittext搜索listview。但它不起作用!当我在edittext中输入任何内容时,没有任何反应,listview保持不变。它没有变化。

这是我尝试过的代码:

public class ListViewAdapter extends BaseAdapter  implements Filterable
{
Activity context;
String title[];
String description[];

public ListViewAdapter(Activity context, String[] title, String[] description) {
    super();
    this.context = context;
    this.title = title;
    this.description = description;
}

public int getCount() {
    // TODO Auto-generated method stub
    return title.length;
}

public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

private class ViewHolder {
    TextView txtViewTitle;
    TextView txtViewDescription;
}

public View getView(int position, View convertView, ViewGroup parent)
{
    // TODO Auto-generated method stub
    ViewHolder holder;
    LayoutInflater inflater =  context.getLayoutInflater();

    if (convertView == null)
    {
        convertView = inflater.inflate(R.layout.listitem_row, null);
        holder = new ViewHolder();
        holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
        holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtViewTitle.setText(title[position]);
    holder.txtViewDescription.setText(description[position]);

return convertView;
}
@Override
public Filter getFilter() {

    Filter filter = new Filter() {

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            List<String> arrayListNames;
            arrayListNames = (List<String>) results.values;
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            Filter.FilterResults results = new FilterResults();
            ArrayList<String> FilteredArrayNames = new ArrayList<String>();
            List<String> mDatabaseOfNames = null;
            // perform your search here using the searchConstraint String.

            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                String dataNames = mDatabaseOfNames.get(i);
                if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                    FilteredArrayNames.add(dataNames);
                }
            }

            results.count = FilteredArrayNames.size();
            results.values = FilteredArrayNames;
            Log.e("VALUES", results.values.toString());

            return results;
        }
    };

    return filter;
}
}

和mainActivity

public class MainActivity extends Activity {
final String[] elename ={"Hydrogen","Helium","Lithium","Beryllium","Boron","Carbon","Nitrogen","Oxygen","Flourine","Noen","Sodium","Magnesium","Aluminium","Silicon","Phosphorous","Sulphur","Chlorine","Argon","Potassium","Calcium","Scandium","Titanium","Vanadium","Chromium","Manganese","Iron","Cobalt","Nickel","Copper","Zinc","Gallium","Germanium","Arsenic","Selenium","Bromine","Krypton","Rubidium","Strontium","Yttrium","Zirconium","Niobium","Molybdenum","Technetium","Ruthenium","Rhodium","Palladium","Silver","Cadmium","Indium","Tin","Antimony","Tellurium","Iodine","Xenon","Caesium","Barium","Lanthanum","Cerium","Praseodymium","Neodymium","Promethium","Samarium","Europium","gadoliium","Terbium","Dysprosium","Holmium","Erbium","Thulium","Ytterbium","Lutetium","Hafnium","Tantalum","Tungsten","Rhenium","Osmium","Iridium","Platinum","Gold","Mercury","Thallium","Lead","Bismuth","Polonium","Astatine","Radon","Francium","Radium","Actinium","Thorium","Protactinium","Uranium","Neptunium","Plutonium","Americium","Curium","Berkelium","Californium","Einstenium","Fermium","Mendelevium","Nobelium","Lawrencium","Rutherfordium","Dubnium","Seaborgium","Bohrium","Hassium","Meitnerium","Darmstadtium","Roentgenium","Copernicium","Ununtrium","Ununquadium","Ununpentium","Ununhexium","Ununseptium","Ununoctium"};
final String[] nos = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77","78","79","80","81","82","83","84","85","86","87","88","89","90","91","92","93","94","95","96","97","98","99","100","101","102","103","104","105","106","107","108","109","110","111","112","113","114","115","116","117","118"};
ListViewAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adapter = new ListViewAdapter(this, elename, nos);
    final EditText searchBar = (EditText) findViewById(R.id.searchbar);
    final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
    final ListView navList = (ListView) findViewById(R.id.left_drawer);
    final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.left_drawer_layout);
    navList.setAdapter(adapter);


    navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
            //Change view according to numbers

            drawer.closeDrawer(linearLayout);
        }
    });

    //filter list view after search instantly
    searchBar.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            MainActivity.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {

        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //hide the keyboard after search on touch list view
    navList.setOnScrollListener(new AbsListView.OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            //hide keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(navList.getWindowToken(), 0);
        }

        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        }
    });

    navList.setEmptyView(findViewById(R.id.empty));

}


}

activity_main.cml

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:background="#000000"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Swipe from the left to open the drawer"
        android:id="@+id/textView"
        android:layout_gravity="center" />
</FrameLayout>

<LinearLayout
    android:id="@+id/left_drawer_layout"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_marginLeft="-65dp"
    android:background="#111"
    android:orientation="vertical"
    android:layout_gravity="start" >

    <EditText
        android:id="@+id/searchbar"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:textColor="#bfc2d1"
        android:singleLine="true"
        android:drawableLeft="@drawable/search"
        android:padding="10dp"
        android:background="@drawable/search_bar"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="3dp"
        android:imeOptions="flagNoExtractUi"
        android:hint="Search" >
    </EditText>

<RelativeLayout
    android:id="@+id/empty"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_marginLeft="-65dp"
    android:background="#111"
    android:orientation="vertical"
    android:layout_gravity="start" >
    <TextView
        android:id="@+id/empty_text"
        android:text="@string/notfound"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:textColor="#ffababab"
        android:textSize="15dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:gravity="center">
    </TextView>
    </RelativeLayout>

    <ListView android:id="@+id/left_drawer"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</LinearLayout>

</android.support.v4.widget.DrawerLayout>

请帮助我了解错误并帮助我解决问题。提前谢谢。

0 个答案:

没有答案