1

我想篩選GridView,但問題似乎是以我在View內組織數據的方式。GridView中ArrayAdapter的自定義篩選器

這是我使用的佈局

private GridView list; 

private void loadListView(){ 
    list = (GridView)findViewById(R.id.apps_list); 

    ArrayAdapter<AppDetail> adapter = new ArrayAdapter<AppDetail>(this, R.layout.list_item, apps) { 
     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      if(convertView == null){ 
       convertView = getLayoutInflater().inflate(R.layout.list_item, null); 
      } 

      ImageView appIcon = (ImageView)convertView.findViewById(R.id.item_app_icon); 
      appIcon.setImageDrawable(apps.get(position).icon); 
      appIcon.setTag(apps.get(position).name); 
      TextView appLabel = (TextView)convertView.findViewById(R.id.item_app_label); 
      appLabel.setText(apps.get(position).label); 
      //TextView appName = (TextView)convertView.findViewById(R.id.item_app_name); 
      //appName.setText(apps.get(position).name); 

      return convertView; 
     } 
    }; 

    list.setAdapter(adapter); 
} 

正如你可能已經明白,我過濾設備上安裝的應用程序列表中的代碼。

現在我有一個搜索方法定義在同一個活動。

private void doMySearch(String query){ 

} 

這裏我需要用查詢過濾適配器。當我試圖重新初始化arrayAdapter並使用adapter.getFilter().filter(query); 進行過濾時,它不起作用。

什麼是通過apps.label屬性過濾適配器的方法?

+0

使用[這](https://gist.github.com/pskink/2dd4d17a93caf02ff696533e82f952b0)通用適配器 – pskink

+0

你能告訴我一個用例 – CBeTJlu4ok

+0

嘗試'類MyAdapter擴展MatchableArrayAdapter {...'和覆蓋它的'onBind'和'matches'方法 – pskink

回答

1

這就是我如何解決我的問題。 由於我的過濾器非常基本,我做了自己的循環和過濾,然後將所有這些傳遞給適配器。

private void doMySearch(final String query){ 
    list = (GridView)findViewById(R.id.apps_list); 


    final List<AppDetail> apps_filtered = new ArrayList<>(); 

    for(int q = 0; q < apps.size(); q++){ 
     if(apps.get(q).label.toString().toLowerCase().startsWith(query)) { 
      Log.e("ddd", apps.get(q).label.toString().toLowerCase()); 

      AppDetail app = new AppDetail(); 
      app.label = apps.get(q).label; 
      app.name = apps.get(q).name; 
      app.icon = apps.get(q).icon; 
      apps_filtered.add(app); 
     } 
    } 

    ArrayAdapter<AppDetail> adapter = new ArrayAdapter<AppDetail>(this, R.layout.list_item, apps_filtered) { 
     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      if(convertView == null){ 
       convertView = getLayoutInflater().inflate(R.layout.list_item, null); 
      } 

      ImageView appIcon = (ImageView)convertView.findViewById(R.id.item_app_icon); 
      appIcon.setImageDrawable(apps_filtered.get(position).icon); 
      appIcon.setTag(apps_filtered.get(position).name); 
      TextView appLabel = (TextView)convertView.findViewById(R.id.item_app_label); 
      appLabel.setText(apps_filtered.get(position).label); 
      //TextView appName = (TextView)convertView.findViewById(R.id.item_app_name); 
      //appName.setText(apps_filtered.get(position).name); 

      return convertView; 
     } 
    }; 

    list.setAdapter(adapter); 
}