如何使用扩展 baseadapter 的自定义适配器实现 getfilter() [英] How to implement getfilter() with custom adapter that extends baseadapter

查看:43
本文介绍了如何使用扩展 baseadapter 的自定义适配器实现 getfilter()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的主要活动

package com.javacodegeeks.android.lbs;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import lbs.promotion.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Curve extends Activity {

    private ProgressDialog pDialog;
     JSONParser jParser = new JSONParser();
     ArrayList<HashMap<String, String>> DaftarPromotion = new ArrayList<HashMap<String, String>>();

     private static String url_daftar_promotion = "http://10.0.2.2/webserver_maaug/promotion/daftar_promotion.php";

     String lon = "101.5178";
     String lat = "3.0724";

     public static final String TAG_SUCCESS = "success";
     public static final String TAG_DAFTAR_PROMOTION = "daftar_promotion";
     public static final String TAG_ID_PROMO = "PromoID";
     public static final String TAG_NAMA_PROMO = "PromoName";
     public static final String TAG_LINK_IMAGE_PROMO = "PromoImage";
     public static final String TAG_DESC_PROMO= "PromoDesc";
     public static final String TAG_CATE_PROMO = "PromoCate";
     public static final String TAG_CONT_PROMO = "PromoContact";
     public static final String TAG_DATES_PROMO = "PromoDateStart";
     public static final String TAG_DATEE_PROMO = "PromoDateEnd";

     JSONArray daftar_promotion = null;

     ListView list;

     PromotionListAdapter adapter;

     EditText inputSearch;

     private Curve activity;

     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_curve);
     DaftarPromotion = new ArrayList<HashMap<String, String>>();

      new Activity().execute();
      activity = this;
      list = (ListView) findViewById(R.id.list);

      inputSearch = (EditText) findViewById(R.id.search_box);

      inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                Curve.this.adapter.getFilter().filter(cs);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        }); 




      list.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {
          HashMap<String, String> map = DaftarPromotion.get(position);
          String pna = map.get(TAG_NAMA_PROMO);
          String pde = map.get(TAG_DESC_PROMO);
          String pca = map.get(TAG_CATE_PROMO);
          String pcon = map.get(TAG_CONT_PROMO);
          String pds = map.get(TAG_DATES_PROMO);
          String pdae = map.get(TAG_DATEE_PROMO);



            Toast.makeText(Curve.this, pna +"
" + pde +"
" + pca +"
" + pds +" to " + pdae +"
" + pcon,Toast.LENGTH_LONG).show();

      }
      }); 



      }


     public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.smenu, menu);
            return true;
        }
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
            case R.id.about:
                 Toast.makeText(Curve.this,"Mobile Advertising Application Using GPS V1.0",Toast.LENGTH_LONG).show();
            return true;
            case R.id.search:{
                 Intent intent = new Intent(Curve.this, Search.class);
                 intent.putExtra("lon",lon);
                 intent.putExtra("lat",lat);
                 startActivity(intent);
            //startActivity(new Intent(this, Search.class));

            }
            return true;
            default:
            return super.onOptionsItemSelected(item);
        }
        }

      public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
      adapter = new PromotionListAdapter(activity, daftar);
      list.setAdapter(adapter);
      }

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (resultCode == 100) {
      Intent intent = getIntent();
      finish();
      startActivity(intent);
      }
      }

      class Activity extends AsyncTask<String, String, String> {

      @Override
      protected void onPreExecute() {
      super.onPreExecute();
      pDialog = new ProgressDialog(Curve.this);
      pDialog.setMessage("Please Wait...");
      pDialog.setIndeterminate(false);
      pDialog.setCancelable(false);
      pDialog.show();
      }

      protected String doInBackground(String... args) {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      JSONObject json = jParser.makeHttpRequest(url_daftar_promotion, "GET",params);

      Log.d("All Products: ", json.toString());
      try {
      int success = json.getInt(TAG_SUCCESS);
      if (success == 1) {
           daftar_promotion = json.getJSONArray(TAG_DAFTAR_PROMOTION);
           for (int i = 0; i < daftar_promotion.length();i++){
           JSONObject c = daftar_promotion.getJSONObject(i);
           String PromoID = c.getString(TAG_ID_PROMO);
           String PromoName = c.getString(TAG_NAMA_PROMO);
           String pat = "http://10.0.2.2/webserver_maaug/";
           String PromoImage = pat + c.getString(TAG_LINK_IMAGE_PROMO);
           String PromoDesc = c.getString(TAG_DESC_PROMO);
           String PromoCate = c.getString(TAG_CATE_PROMO);
           String PromoDateStart = c.getString(TAG_DATES_PROMO);
           String PromoDateEnd = c.getString(TAG_DATEE_PROMO);
           String PromoContact = c.getString(TAG_CONT_PROMO);

           HashMap<String, String> map = new HashMap<String, String>();

           map.put(TAG_ID_PROMO, PromoID);
           map.put(TAG_NAMA_PROMO, PromoName);
           map.put(TAG_LINK_IMAGE_PROMO, PromoImage);
           map.put(TAG_DESC_PROMO, PromoDesc);
           map.put(TAG_CATE_PROMO, PromoCate);
           map.put(TAG_DATES_PROMO, PromoDateStart);
           map.put(TAG_DATEE_PROMO, PromoDateEnd);
           map.put(TAG_CONT_PROMO, PromoContact);

           DaftarPromotion.add(map);
           }

           } else {
           }
           } catch (JSONException e) {
           e.printStackTrace();
           }
           return null;
           }

           protected void onPostExecute(String file_url) {
           pDialog.dismiss();
           runOnUiThread(new Runnable() {
           public void run() {

           SetListViewAdapter(DaftarPromotion);




                }
           });
        }
    }
    }

这是我的自定义适配器,它非常简单,没有自己的对象类

and this is my custom adapter, it is a very simple one, without an object class of it's own

package lbs.promotion;

import java.util.ArrayList;
import java.util.HashMap;

import com.javacodegeeks.android.lbs.Curve;
import com.javacodegeeks.android.lbs.R;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

public class PromotionListAdapter extends BaseAdapter {

 private Activity activity;
 private ArrayList<HashMap<String, String>> data;
 private static LayoutInflater inflater = null;
 public ImageLoader imageLoader;

 public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {

 activity = a;
 data = d;
 inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 imageLoader = new ImageLoader(activity.getApplicationContext());
 }

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

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

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

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

     View vi = convertView;
      if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);

      TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
      TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
      TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
      TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
      TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
      TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
      TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
      TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
      ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);

      HashMap<String, String> daftar_promotion = new HashMap<String, String>();
      daftar_promotion = data.get(position);

      PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));

      PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));

      PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));

      PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));

      PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));

      PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));

      PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));

      PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));

      imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);

      return vi;

      }




}

这是我的 layout.xml

here is my layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

 <!-- Editext for Search -->
    <EditText android:id="@+id/search_box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="type to search"
        android:inputType="text"
        android:maxLines="1"/>

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#040404"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector" />

</LinearLayout>

我如何让 getfilter() 函数工作?或者有什么更简单的方法可以在我的列表视图中实现过滤?我想根据我的 PromoName 进行过滤

how do i get the getfilter() function working? or is there any simpler way to implement filtering in my listview? i want to filter based on my PromoName

推荐答案

过滤器有两个主要组件,performFiltering(CharSequence) 方法和 publishResults(CharSequence, FilterResults)代码>方法.在您的 PromotionListAdapter 中,您需要实现 Filterable 接口,然后覆盖 getFilter() 方法以返回一个实现了这些方法的新过滤器.

A Filter has two major components, the performFiltering(CharSequence) method and the publishResults(CharSequence, FilterResults) method. In your PromotionListAdapter, you'll need to implement the Filterable interface then Override the getFilter() method to return a new Filter that has these methods implemented.

performFiltering(CharSequence) 方法是您完成大部分工作的地方.CharSequence 参数是您要过滤的数据.在这里,您首先要确定是否应该将列表作为基本情况进行过滤.决定执行过滤后,为过滤后的数据集创建一个新的 ArrayList(在您的情况下,一个新的 ArrayList>),并循环遍历您的完整列表项集,将与过滤器匹配的值添加到您的新 ArrayList.

The performFiltering(CharSequence) method is where you'll do the bulk of your work. The CharSequence argument is the data which you're filtering on. Here, you'll first want to determine if the list should even be filtered as the base case. Once you've decided to perform the filtering, create a new ArrayList for your filtered dataset (in your case, a new ArrayList>), and loop through your complete set of list items, adding the values that match the filter to your new ArrayList.

performFiltering 方法的返回类型是 FilterResults.FilterResults 是一个简单的对象,有两个变量,int countObject results.performFiltering 使用过滤后的数据创建新的 ArrayList 后,创建一个新的 FilterResults,将新的 ArrayList 设置为结果,并将该 ArrayList 的大小设置为计数.

The return type for the performFiltering method is FilterResults. FilterResults is a simple object with two variables, int count and Object results. Once performFiltering has created the new ArrayList with the filtered data, create a new FilterResults, setting your new ArrayList as results and the size of that ArrayList as count.

publishResults(CharSequence, FilterResults) 方法在 performFiltering() 返回后被调用.CharSequence 参数与您过滤的字符串相同.FilterResults 参数是从 performFiltering() 返回的.在此方法中,您需要将新的 ArrayList 设置为 List 的数据源,然后调用 notifyDataSetChanged() 来更新 UI.

The publishResults(CharSequence, FilterResults) method is called after performFiltering() returns. The CharSequence parameter is the same String you were filtering on. The FilterResults parameter is the return from performFiltering(). In this method, you'll want to set your new ArrayList as the data source for your List and then call notifyDataSetChanged() to update the UI.

为了实现这一点,当我的适配器同时跟踪数据的原始 ArrayList 和当前显示的过滤的 ArrayList 时,我取得了成功.下面是一些基于您的适配器的样板代码,可以帮助您入门.我已在重要行上方发表评论.

In order to implement this, I've had success when my Adapter keeps track of both the original ArrayList of data and a filtered ArrayList of what is currently being shown. Here's some boilerplate code based on your adapter that can help get you started. I've commented above important lines.

public class PromotionListAdapter extends BaseAdapter implements Filterable
{
    private Activity activity;
    private static LayoutInflater inflater = null;
    public ImageLoader imageLoader;

    //Two data sources, the original data and filtered data
    private ArrayList<HashMap<String, String>> originalData;
    private ArrayList<HashMap<String, String>> filteredData;

    public PromotionListAdapter(Activity a, ArrayList<HashMap<String, String>> d) 
    {
        activity = a;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(activity.getApplicationContext());

        //To start, set both data sources to the incoming data
        originalData = d;
        filteredData = d;
    }

    //For this helper method, return based on filteredData
    public int getCount() 
    {
        return filteredData.size();
    }

    //This should return a data object, not an int
    public Object getItem(int position) 
    {
        return filteredData.get(position);
    }

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

    //The only change here is that we'll use filteredData.get(position)
    //Even better would be to use getItem(position), which uses the helper method (see the getItem() method above)
    public View getView(int position, View convertView, ViewGroup parent) 
    {

       View vi = convertView;
       if (convertView == null)vi = inflater.inflate(R.layout.item_list_promotion, null);

      TextView PromoID = (TextView) vi.findViewById(R.id.PromoID);
      TextView PromoName = (TextView) vi.findViewById(R.id.PromoName);
      TextView PromoImage = (TextView) vi.findViewById(R.id.PromoImage);
      TextView PromoDesc = (TextView) vi.findViewById(R.id.PromoDesc);
      TextView PromoCate = (TextView) vi.findViewById(R.id.PromoCate);
      TextView PromoContact = (TextView) vi.findViewById(R.id.PromoContact);
      TextView PromoDateStart = (TextView) vi.findViewById(R.id.PromoDateStart);
      TextView PromoDateEnd = (TextView) vi.findViewById(R.id.PromoDateEnd);
      ImageView thumb_image = (ImageView) vi.findViewById(R.id.image_promo);

      HashMap<String, String> daftar_promotion = new HashMap<String, String>();

      //Get data from filtered Data
      //This line can be replaced with:
      //     daftar_promotion = getItem(position);
      daftar_promotion = filteredData.get(position);

      PromoID.setText(daftar_promotion.get(Curve.TAG_ID_PROMO));

      PromoName.setText(daftar_promotion.get(Curve.TAG_NAMA_PROMO));

      PromoImage.setText(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO));

      PromoDesc.setText(daftar_promotion.get(Curve.TAG_DESC_PROMO));

      PromoCate.setText(daftar_promotion.get(Curve.TAG_CATE_PROMO));

      PromoContact.setText(daftar_promotion.get(Curve.TAG_CONT_PROMO));

      PromoDateStart.setText(daftar_promotion.get(Curve.TAG_DATES_PROMO));

      PromoDateEnd.setText(daftar_promotion.get(Curve.TAG_DATEE_PROMO));

      imageLoader.DisplayImage(daftar_promotion.get(Curve.TAG_LINK_IMAGE_PROMO),thumb_image);

      return vi;

    }

    @Override
    public Filter getFilter()
    {
       return new Filter()
       {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence)
            {
                FilterResults results = new FilterResults();

                //If there's nothing to filter on, return the original data for your list
                if(charSequence == null || charSequence.length() == 0)
                {
                    results.values = originalData;
                    results.count = originalData.size();
                }
                else
                {
                    ArrayList<HashMap<String,String>> filterResultsData = new ArrayList<HashMap<String,String>>();

                    for(HashMap<String,String> data : originalData)
                    {
                        //In this loop, you'll filter through originalData and compare each item to charSequence.
                        //If you find a match, add it to your new ArrayList
                        //I'm not sure how you're going to do comparison, so you'll need to fill out this conditional
                        if(data matches your filter criteria)
                        {
                            filterResultsData.add(data);
                        }
                    }            

                    results.values = filterResultsData;
                    results.count = filteredResultsData.size();
                }

                return results;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults)
            {
                filteredData = (ArrayList<HashMap<String,String>>)filterResults.values;
                notifyDataSetChanged();
            }
        };
    }
}

这就给你了!据我所知,您已经为正确设置的 inputText EditText 实现了 TextWatcher,因此添加 getFilter() 方法并对您的适配器进行一些其他小的更改应该会引导您一个解法.我相信您还可以在您的 Adapter 上为您的过滤器创建一个成员变量,因此您不会在每次调用 getFilter() 时都创建该类的新实例,但是我从我以前的项目中复制/粘贴了它,并且是确定它是这样工作的.玩它,看看什么对你有用!希望这可以帮助!如果您需要澄清任何内容,请发表评论.

And there you have it! As far as I can tell, you've already implemented the TextWatcher for your inputText EditText set up properly, so adding the getFilter() method and making a few other minor changes to your Adapter should lead you to a solution. I believe you can also create a member variable on your Adapter for your Filter, so you're not creating a new instance of the class each time getFilter() is called, but I copy/pasted this from a previous project of mine and am sure it works this way. Play with it and see what works for you! Hope this helps! And please do comment if you need anything clarified.

这篇关于如何使用扩展 baseadapter 的自定义适配器实现 getfilter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆