0

我正在尝试做一个搜索栏,根据用户输入的关键字过滤列表视图,代码没有错误,但根本没有过滤。知道问题可能是什么吗?我尝试了各种方法,但都没有成功。

创建

super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.layout_main);

// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
EditText search = (EditText)findViewById(R.id.EditText01);

mListAppInfo.setTextFilterEnabled(true);

// create new adapter
final AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());


// set adapter to list view  
mListAppInfo.setAdapter(adapter);


search.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {

    }

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

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        Log.e("TAG", "ontextchanged");
       adapter.getFilter().filter(s); //Filter from my adapter
       adapter.notifyDataSetChanged(); //Update my view
    }
});

ArrayAdapter 类

public class AppInfoAdapter extends ArrayAdapter<ApplicationInfo> {

    private Context mContext;
    PackageManager mPackManager;

    public AppInfoAdapter(Context c, List<ApplicationInfo> list, PackageManager pm) {
        super(c, 0, list);
        mContext = c;
        mPackManager = pm;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // get the selected entry
        ApplicationInfo entry = (ApplicationInfo) getItem(position);

        Log.e("TAG", entry.toString());

        // reference to convertView
        View v = convertView;

        // inflate new layout if null
        if(v == null) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            v = inflater.inflate(R.layout.layout_appinfo, null);
        }

        // load controls from layout resources
        ImageView ivAppIcon = (ImageView)v.findViewById(R.id.ivIcon);
        TextView tvAppName = (TextView)v.findViewById(R.id.tvName);
        TextView tvPkgName = (TextView)v.findViewById(R.id.tvPack);

        // set data to display
        ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
        tvAppName.setText(entry.loadLabel(mPackManager));
        tvPkgName.setText(entry.packageName);

        // return view
        return v;
    }
}
4

2 回答 2

1

有两种可能的方法来解决这个问题

1.使用自己的过滤算法过滤适配器。有关详细信息,请参阅此博文 http://www.mokasocial.com/2010/07/arrayadapte-filtering-and-you/

2. 第二种更简单的方法是覆盖您可能已经定义的 Custom RowItem 类中的 tostring 方法

 @Override
        public String toString() {
            return name + "\n" + description;
        }

并使用 adapter.getFilter().filter(s); 因此,您正在使用它现在可以工作,因为您的适配器现在返回一个有效的字符串来过滤

于 2013-07-25T10:40:55.483 回答
0

调用adapter.getFilter().filter(s)使用 ArrayAdapter 的默认String过滤逻辑,但由于您的列表类型是 of ApplicationInfo,因此 ArrayAdapterApplicationInfo#toString()用于项目比较
,这看起来不像您想要过滤的东西

于 2012-07-26T11:33:56.137 回答