首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用扩展baseadapter的自定义适配器实现getfilter()

如何使用扩展baseadapter的自定义适配器实现getfilter()
EN

Stack Overflow用户
提问于 2013-01-16 19:07:13
回答 2查看 35K关注 0票数 16

这是我的主要活动

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 +"\n" + pde +"\n" + pca +"\n" + pds +" to " + pdae +"\n" + 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);




                }
           });
        }
    }
    }

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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进行过滤

EN

回答 2

Stack Overflow用户

发布于 2013-01-16 22:48:02

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

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

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

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

为了实现这一点,当我的适配器同时跟踪数据的原始ArrayList和当前显示内容的过滤ArrayList时,我已经取得了成功。这里有一些基于您的适配器的样板代码,可以帮助您入门。我已经对上面的重要代码进行了注释。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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()时都创建一个新的类实例,但是我从我以前的一个项目中复制/粘贴了这个实例,并且确信它是这样工作的。试着使用它,看看什么对你有效!希望这能有所帮助!如果你有任何需要澄清的地方,请发表评论。

票数 60
EN

Stack Overflow用户

发布于 2013-01-17 00:03:29

您的适配器需要实现Filterable。

有关这方面(和listView)的更多信息,请观看视频"the world of listView

下面是一个示例代码:

http://codetheory.in/android-filters/

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14365847

复制
相关文章
Maven通过命令创建web项目
mvn archetype:create -DgroupId=com.learn -DartifactId=LearnNew -DarchetypeArtifactId=maven-archetype-webapp
程序新视界
2022/11/30
3180
Maven通过命令创建web项目
在idea中创建web项目_idea部署web项目
这个时候给项目命名,我在这里命名为java_web,下面那个可以更改项目存放的路径,我这里放到自定的路径,点击Finish。
全栈程序员站长
2022/08/02
1.6K0
在idea中创建web项目_idea部署web项目
IDEA 创建Maven Web项目时很慢
最近创建web项目,很慢,还会创建失败,忍不住了,苦思冥想排查原因, 最后,终于找到了,是因为maven 没有选择jdk的原因! 气死我了。
无敌小菜鸟
2020/05/09
8700
对路径“xxxxx”的访问被拒绝。
对路径“D:\\Weixin\\WechatWeb\\wapMxApi\\JsonFile\\WaterPrice.json”的访问被拒绝。
全栈程序员站长
2022/09/20
2.7K0
部署docsify项目时出现无法访问README.md
今天在服务器上部署用docsify编写的文档项目,结果发现首页竟然无法显示,提示404。
用户8851537
2021/08/03
1.9K1
拒绝访问磁盘拒绝访问的恢复办法
当磁盘插入电脑中时,如果示“拒绝访问”的信息时,我们首先需要对磁盘进行目录修复操作。插入待修复的磁盘,打开“我的电脑”,找到磁盘所在的盘符。
用户10127983
2022/10/22
3K0
【Tomcat】Linux上Tomcat发布-JavaWeb项目-访问时不通过项目名
一开始自己不知道怎么直接通过域名访问到自己部署的Web项目,发布在Tomcat上的。 因为自己以前写都是后面加了项目名, 然后去百度谷歌,找到了下面的正确方法
谙忆
2021/01/21
1.2K0
【Tomcat】Linux上Tomcat发布-JavaWeb项目-访问时不通过项目名
从拒绝到被拒绝
2021,新的一轮工作季的开始,你投了太多的简历,太多的邮件,太多的尝试,而到头来收获的却是从拒绝到拒绝。
HoneyMoose
2021/05/13
1.1K0
从拒绝到被拒绝
为什么使用了HTTP代理还是被拒绝访问?
既然某乎为我推荐了这个问题,那今天就来简单说说,使用了HTTP代理后,还是拒绝访问,无非以下原因:
阿秋数据采集
2023/05/19
2.1K0
怎么创建web项目_vs怎么创建项目
WTM — Rapid development framework based on dotnet core
全栈程序员站长
2022/11/03
4.1K0
scrapy拒绝访问
运行成功
红目香薰
2022/11/29
2.8K0
scrapy拒绝访问
maven创建web项目
链接:https://my.oschina.net/960823/blog/870511
斯文的程序
2019/11/07
1K0
maven创建web项目
MySql拒绝访问
昨天用phpMyAdmin修改账号密码后,出现了下图的情况 原来,用phpmyadmin链接mysql数据库,并修改mysql数据库的密码。但修改的方式是直接在表里面进行修改保存。没有用sql语句。
smy
2018/04/03
5.8K0
MySql拒绝访问
github部署项目,在线访问
5,关联github仓库,获取到github仓库地址后,将本地仓库与github仓库关联
用户3055976
2019/12/30
9990
github部署项目,在线访问
flutter项目打包web访问
参考文章:https://dart.cn/null-safety/migration-guide
徐建国
2021/11/30
2.4K0
flutter项目打包web访问
Docker部署web项目
  docker是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的linux机器上,也可以实现虚拟化。容器是完全使用沙箱机制,相互之间不会有任何接口。
程序员云帆哥
2022/05/12
1.9K0
Docker部署web项目
服务器要删除文件访问被拒绝,删除文件提示:文件夹访问被拒绝 需要来自administrator权限执行操作…
有时候我们在删除一些系统重要文件,或者被保护的文件的时候,会出现对话框,提示我们您需要来自administrator权限才能对此文件夹进行更改,这是什么原因导致的?今天小编就为大家分析下解决办法。
全栈程序员站长
2022/11/17
6K0
服务器要删除文件访问被拒绝,删除文件提示:文件夹访问被拒绝 需要来自administrator权限执行操作…
电脑拒绝访问_添加本地端口拒绝访问win10
1:linux 服务器默认是不允许 root账号进行远程使用winscp,所以我们需要创建一个新的非root用户进行登录
全栈程序员站长
2022/09/30
2.5K0
电脑拒绝访问_添加本地端口拒绝访问win10
通过Jenkins部署java项目
Jenkins大多数情况下都是用来部署Java项目,Java项目有一个特点是需要编译和打包的,一般情况下编译和打包都是用maven完成,所以系统环境中需要安装maven。
端碗吹水
2020/09/23
1.3K0
通过Jenkins部署java项目
通过域名访问Linux云服务器上的java web项目
当有几个项目需要放在云服务器上,直接在nginx配置文件中创建几个虚拟主机,然后需要解析几个二级域名。这种方法比较容易实现些,把所有的java web项目放到一个Tomcat下实现访问。
兮动人
2021/06/11
10.8K0

相似问题

创建虚拟目录时拒绝访问。

15

在通过jenkins localhost tomcat部署时被拒绝访问

12

Maven:无法部署项目,访问被拒绝

33

生成项目时访问被拒绝

31

使用XML文档部署Web项目时,构建服务器上的“访问被拒绝”

39
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文