0

我们需要在这个例子中实现过滤列表视图的代码。我们使用了 2 个类:(Car.java包含 Object Car),ClassCarAdapter扩展了BaseAdapterClass。下面是一些代码:

汽车.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)));

}   
}

谢谢您的帮助。

4

1 回答 1

1

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

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

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

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

于 2013-09-20T09:52:08.327 回答