【问题标题】:Android Filter ListView Using BaseAdapterAndroid 使用 BaseAdapter 过滤 ListView
【发布时间】:2013-03-28 08:55:13
【问题描述】:

我们需要在这个例子中实现过滤列表视图的代码。我们使用了 2 个类:Car.java(包含对象车),CarAdapter 类扩展了 BaseAdapter 类。 以下是部分代码:

Car.java

public class Car {

public String title;
public int car_id;

public Car(String title,int car_id) {
    this.title = title;
    this.car_id = car_id;
}

}

CarAdapter.java

public class CarAdapter extends BaseAdapter {

private List<Car> mCarList;
private LayoutInflater mInflater;

public CarAdapter(List<Car> list, LayoutInflater inflater) {
    mCarList = list;
    mInflater = inflater;
}

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

@Override
public Object getItem(int position) {
    return mCarList.get(position);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewItem item;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.prototype, null);
        item = new ViewItem();


        item.CarTitle = (TextView) convertView
                .findViewById(R.id.TextViewPrototype);

        convertView.setTag(item);
    } else {
        item = (ViewItem) convertView.getTag();
    }

    Car curCar = mCarList.get(position);

    item.CarTitle.setText(curCar.title);    

    return convertView;
}

private class ViewItem {
    TextView CarTitle;
}

}

CarActivity.java

 public class ActivityCar extends Activity {

private List<Car> mCarList;
private EditText et;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.car);
    // Obtain a reference to the product catalog
    mCarList = CarHelper.getCar(getResources());
    // Create the list
    ListView listViewCatalog = (ListView) findViewById(R.id.list_car);
    listViewCatalog.setAdapter(newCarAdapter(mCarList,getLayoutInflater)));

}   
}

感谢您的帮助。

【问题讨论】:

  • 你的问题是......如何过滤数据??
  • 没错。如何过滤listview中的数据(包含car.title)

标签: android listview filter baseadapter


【解决方案1】:

按照以下步骤使列表视图可过滤:

  1. CarAdapter.java 中实现Filterable 接口。看看here回答的类似问题。

  2. CarActivity.java 中将 Listview 适配器设置为可过滤。
    listViewCatalog.setTextFilterEnabled(true);

  3. 如果您使用了android.widget.SearchView,则实现SearchView.OnQueryTextListener,或者如果您使用EditText,则实现TextWatcher接口。

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2012-09-09
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    相关资源
    最近更新 更多