-1

现在我想制作过滤器,但我真的不知道该怎么做。我已经阅读了一些教程并尝试过,但它仍然无法正常工作。请帮我!我想实现搜索功能。

类 apdater 的代码:

public class PlaceAdapter extends BaseAdapter {
private static ArrayList<Place> searchArrayList;

private LayoutInflater mInflater;

public PlaceAdapter(Context context, ArrayList<Place> results) {
    searchArrayList = results;
    mInflater = LayoutInflater.from(context);
}

public int getCount() {
    return searchArrayList.size();
}

public Object getItem(int position) {
    return searchArrayList.get(position);
}

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

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.row, null);
        holder = new ViewHolder();
        holder.txtName = (TextView) convertView
                .findViewById(R.id.label_place);
        holder.txtAddress = (TextView) convertView
                .findViewById(R.id.label_address);
        holder.txtPhone = (TextView) convertView
                .findViewById(R.id.label_distance);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.txtName.setText(searchArrayList.get(position).getName());
    holder.txtAddress.setText(searchArrayList.get(position).getAddress());
    holder.txtPhone.setText(searchArrayList.get(position).getPhone());

    return convertView;
}

static class ViewHolder {
    TextView txtName;
    TextView txtAddress;
    TextView txtPhone;
}

}

班级活动代码

public class ServiceDetail extends Activity {

private String DB_NAME = "Danang Travel.sqlite";
private PlaceAdapter adapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.servicedetail);

    final ArrayList<Place> searchResults = GetSearchResults();

    final EditText filterEditText = (EditText) findViewById(R.id.filter_text);
    final ListView lvPlace = (ListView) findViewById(R.id.listView1);

    adapter = new PlaceAdapter(this, searchResults);
    lvPlace.setAdapter(adapter);
    lvPlace.setTextFilterEnabled(true);

    // Set Focus*****************************************
    lvPlace.setFocusableInTouchMode(true);
    lvPlace.requestFocus();
    lvPlace.setOnFocusChangeListener(new OnFocusChangeListener() {

        public void onFocusChange(View arg0, boolean arg1) {
            // TODO Auto-generated method stub
            // arg0.setBackgroundColor(arg1 ? Color.GRAY : Color.BLACK);
            // lvPlace.setItemsCanFocus(true);
        }

    });

    // lvPlace.setClickable(true);

    /******************************************************/
    // filter search
    filterEditText.addTextChangedListener(new TextWatcher() {

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


        }

        public void beforeTextChanged(CharSequence arg0, int arg1,
                int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

    lvPlace.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> a, View v, int position,
                long id) {
            Object o = lvPlace.getItemAtPosition(position);
            Place fullObject = (Place) o;
            Toast toast = Toast.makeText(ServiceDetail.this,
                    "You have chosen: " + " " + fullObject.getName(),
                    Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
        }
    });

}

private ArrayList<Place> GetSearchResults() {
    ArrayList<Place> results = new ArrayList<Place>();

    SQLiteDatabase DB = null;
    Intent t = getIntent();
    Bundle extra = t.getExtras();
    String temp = extra.getString("k");
    try {
        DB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);

        Cursor c = DB.rawQuery(
                "SELECT Name,Address,TypeID FROM ServiceDetail Where SerID = '"
                        + temp + "' ORDER BY Name", null);

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            Place k = new Place();
            // The Cursor is now set to the right position
            String n = c.getString(c.getColumnIndex("Name"));
            String a = c.getString(c.getColumnIndex("Address"));
            String p = c.getString(c.getColumnIndex("TypeID"));

            k.setName(n);
            k.setAddress(a);
            k.setPhone(p);
            results.add(k);
        }

    } catch (SQLiteException se) {
        Log.e(getClass().getSimpleName(),
                "Could not create or Open the database");

    } finally {
        DB.close();
    }

    return results;
}

}

现在我想制作过滤器,但我真的不知道该怎么做。我已经阅读了一些教程并尝试过,但它仍然无法正常工作。请帮我!

4

1 回答 1

0

干得好 :)

    //Firstly here is your edittext on which you want to filter
    EditTextfilterText = (EditText) findViewById(R.id.search_box);
    filterText.clearComposingText();
    //Give the edittext the watcher as a text listener
    filterText.addTextChangedListener(filterTextWatcher);

//This will listen to key events such as you entering something inside the edit text
private TextWatcher filterTextWatcher = new TextWatcher() {


    public void afterTextChanged(Editable s) {
        //Called after text changed
    }

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

    //Called each time you enter something into the edittext to filter your list or whatever
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {

                //Adapter creating code
                      //......
                //Filter calling code
                adapter.getFilter().filter(s, new FilterListener() {
                @Override
                public void onFilterComplete(int count) {
                    //Just for fun do something here once filtering is done
                }
            });


        }
    }

};

现在在您的自定义适配器中,您将拥有以下内容:


 public Filter getFilter() {

        filter = new DrugListFilter();

    return filter;
}


private class MyFilterName extends Filter{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults retval = new FilterResults();
                    ArrayList<something> filt = new ArrayList<something>();

                    //... Some code to filter your current Adapter data by the constaint
                    //Pass the results to retval
                    retval.count = filt.size();
                    retval.values = filt;
                       }
                    //return retval
                return retval;
        }

    //This is called once performFiltering is done
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredItems.clear();
                    //This is your array of filtered items
        filteredItems.addAll((ArrayList)results.values);
        doneFilter = true;
                    //Notify the dataset that it needs to update
        notifyDataSetChanged();

    }
}
于 2012-09-24T18:59:53.880 回答