2014-10-31 3 views
1

В моем приложении я создал собственное представление списка, и я хочу реализовать фильтр, чтобы список можно было фильтровать в соответствии с текстом, введенным в EditText. Я использую BaseAdapter как отдельный класс.listview custom from json getfilter

это мой адаптер:

общественного класса MyAdapter расширяет BaseAdapter {

// Declare Variables 
Context context; 
LayoutInflater inflater; 
ArrayList<HashMap<String, String>> data; 
ImageLoader imageLoader; 
public HashMap<String, String> resultp; 

public AllProductAdapter(Context context, 
     ArrayList<HashMap<String, String>> arraylist) { 
    this.context = context; 
    data = arraylist; 
    imageLoader = new ImageLoader(context); 

} 

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

public Object getItem(int position) { 
    return null; 
} 

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

public View getView(final int position, View convertView, ViewGroup parent) { 

    // Declare Variables 
    TextView namaBarang; 
    ImageView image; 
    TextView harga; 
    ImageButton cart; 

    inflater = (LayoutInflater) context 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View itemView = inflater.inflate(R.layout.listview_viewitem, parent, 
      false); 
    // Get the position from the results 
    resultp = new HashMap<String, String>(); 
    resultp = data.get(position); 

    // Locate the TextViews in listview_item.xml 
    namaBarang = (TextView) itemView.findViewById(R.id.judul); 
    cart = (ImageButton) itemView.findViewById(R.id.cart); 
    harga = (TextView) itemView.findViewById(R.id.posterFile); 
    image = (ImageView) itemView.findViewById(R.id.poster); 

    // Capture position and set results to the TextViews 
    namaBarang.setText(resultp.get(AllProductAgent.TITLE)); 

    harga.setText(resultp.get(AllProductAgent.HARGA), 
      TextView.BufferType.SPANNABLE); 

    Spannable spannable = (Spannable) harga.getText(); 
    spannable.setSpan(new StrikethroughSpan(), 0, 
      resultp.get(AllProductAgent.HARGA).length(), 
      Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

    // Capture position and set results to the ImageView 
    // Passes flag images URL into ImageLoader.class to download and cache 
    // images 
    imageLoader 
      .DisplayImageList(resultp.get(AllProductAgent.GAMBAR), image); 

    // Link to Register Screen 
    itemView.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 

     } 
    }); 

    // Add ArrayList 
    cart.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View view) { 
      // Get the position from the results 
      HashMap<String, String> resultp = new HashMap<String, String>(); 
      resultp = data.get(position); 

      // show toast if item was been added to cart 
      Toast.makeText(
        context, 
        resultp.get(AllProductAgent.TITLE) 
          + " has been added to Cart", Toast.LENGTH_LONG) 
        .show(); 

      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("nama", resultp.get(AllProductAgent.TITLE)); 
      map.put("harga", resultp.get(AllProductAgent.HARGA)); 
      map.put("link_gambar", resultp.get(AllProductAgent.GAMBAR)); 
      map.put("website", resultp.get(AllProductAgent.WEBSITE)); 
      BaseActivity.cartList.add(map); 

     } 
    }); 
    itemView.setBackgroundColor(position % 2 == 0 ? Color 
      .parseColor("#c7eaf8") : Color.parseColor("#FFFFFF")); 

    return itemView; 
} 

как я могу фильтруется свои приложения? Я пытаюсь так много кода и до сих пор не могу его получить.

благодаря

+0

ваш список адаптер должен реализовать интерфейс Фильтруемые – pskink

+0

я знаю, что, но я уже стараюсь много и я все еще не в состоянии фильтровать мой адаптер. ты знаешь как? спасибо – zacky

+0

уверен, см. мой ответ здесь: http://stackoverflow.com/questions/19858843/how-to-dynamically-add-suggestions-to-autocompletetextview-with-preserving-chara – pskink

ответ

1

Установите TextChangedListener в Searchedittext

Searchtxt.addTextChangedListener(new TextWatcher() { 

      @Override 
      public void onTextChanged(CharSequence s, int start, 
        int before, int count) { 

       ListAdapterview.getFilter().filter(s.toString()); 
      } 

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

      } 

      @Override 
      public void afterTextChanged(Editable s) { 
      } 
     }); 

Затем Реализовать "Фильтруемый" в классе адаптера

Затем Добавьте этот код

@SuppressLint("DefaultLocale") 
private class ItemFilter extends Filter { 
    @Override 
    protected FilterResults performFiltering(CharSequence constraint) { 

     String filterString = constraint.toString().toLowerCase(); 

     FilterResults results = new FilterResults(); 

     final ArrayList<HashMap<String, String>> list = data; 

     int count = list.size(); 
     final ArrayList<HashMap<String, String>> filtereddata = new ArrayList<HashMap<String, String>>(); 

     String filterableString; 

     for (int i = 0; i < count; i++) { 
      filterableString = list.get(i).get("ur item name"); 
      if (filterableString.toString().toLowerCase().contains(filterString)) { 
       filtereddata.add(list.get(i)); 
      } 
     } 

     results.values = filtereddat; 
     results.count = filtereddat.size(); 

     return results; 
    } 

    @SuppressWarnings("unchecked") 
    @Override 
    protected void publishResults(CharSequence constraint, 
      FilterResults results) { 
     if (results != null) { 
      if (results.count > 0) { 
       data = new ArrayList<HashMap<String,String>>((ArrayList<HashMap<String, String>>) results.values) ; 
      } 

     } 
     notifyDataSetChanged(); 
    } 

} 
+0

эй, я все еще получаю ошибку. . в ListAdapterview.getFilter(). filter (s.toString()); это моя ошибка: метод getFilter() не определен для типа ListAdapterview. вы знаете почему? спасибо – zacky

+0

Измените свой базовый адаптер на ArrayAdapter > – Siva

+0

открытый класс AllProductAdapter расширяет ArrayAdapter > реализует Filterable. вы имеете в виду вот так? все еще ошибка :( – zacky

0

Предположим, что у вас есть EditText с id = "field1"

Field1 = (EditText)findViewById(R.id.field1); 
Field1.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) { 
     /* WORK HERE TO FILTER */ 
    } 
}); 

Теперь в OnTextChanged методе вы можете фильтровать данные (данные должны быть ArrayList экземпляра, используемый адаптером) наилучшим образом, что вы можете знать (вы можете использовать пользовательскую функцию или реализует фильтр) а затем обновите адаптер, чтобы обновить список &.

public void onTextChanged(CharSequence s, int start, int before, int count) { 
    /* WORK HERE TO FILTER */ 
    doFilter(data); 
    MyAdapterInstance.notifyDataSetChanged(); 
} 
+0

Я пробовал это и какой метод dofilter? – zacky

+0

doFilter() - это метод, который вы должны использовать для настраиваемого фильтра. Если вы хотите реализовать собственный фильтр, вы можете создать свою собственную функцию doFilter(). функция должна делать, зависит от вашей цели! –

Смежные вопросы