当前位置: 首页 > 知识库问答 >
问题:

实现getFilter()。带有AsyncTask的自定义ArrayAdapter

鱼阳伯
2023-03-14

java代码:

public class c_DTArtikel_allforsearch extends Activity implements AdapterView.OnItemClickListener {

private ListView ListViewLayout;
private EditText search;
private String[] Name;
private String[] Number;
private int[] ImagesID;
private ArrayList<Article> articleList = new ArrayList<Article>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_lv_search);


    Resources res = getResources();

    String[] saugname = res.getStringArray(R.array.SauglanzeName);
    String[] pumpmname = res.getStringArray(R.array.PumpMName);

    String[] saugnummer = res.getStringArray(R.array.SauglanzeNumber);
    String[] pumpmnummer = res.getStringArray(R.array.PumpMNummer);

    TypedArray saugimg = res.obtainTypedArray(R.array.SauglanzeImg);
    TypedArray pumpmimg = res.obtainTypedArray(R.array.PumpeMImg);

    ArrayList<String> name = new ArrayList<String>();
    name.addAll(Arrays.asList(saugname));
    name.addAll(Arrays.asList(pumpmname));
    Name = name.toArray(new String[saugname.length+pumpmname.length]);

    ArrayList<String> number = new ArrayList<String>();
    number.addAll(Arrays.asList(saugnummer));
    number.addAll(Arrays.asList(pumpmnummer));
    Number = number.toArray(new String[saugnummer.length+pumpmnummer.length]);

    ArrayList<Integer> imgInts = new ArrayList<Integer>();
    int nr = -1;
    while ( ++nr < saugimg.length() )
        imgInts.add (saugimg.getResourceId(nr, 0));
    nr = -1;
    while ( ++nr < pumpmimg.length() )
        imgInts.add (pumpmimg.getResourceId(nr, 0));
        ImagesID = new int[imgInts.size()];
    for (int i=0; i < imgInts.size(); i++)
    {
        ImagesID[i] = ((Integer) imgInts.get(i)).intValue();
    }


    Search = (EditText) findViewById(R.id.EditTextSearch);

    ListViewLayout = (ListView) findViewById(R.id.listViewLayoutSearch);

    final TIAdapter adapter = new TIAdapter(articleList, this);
    ListViewLayout.setAdapter(adapter);
    ListViewLayout.setOnItemClickListener(this);

    //has been missing
        for (int i = 0; i < Name.length; i++)
    {
        Article a = new Article(Name[i], Number[i], ImagesID[i]);
        // Binds all strings into an array
        articleList.add(a);
    }

    // Add Text Change Listener to EditText
   search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            System.out.println("Text ["+s+"] - Start ["+start+"] - Before ["+before+"] - Count ["+count+"]");
            if (count < before) {
                // We're deleting char so we need to reset the adapter data
                adapter.resetData();
            }

            adapter.getFilter().filter(s.toString());

        }

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

        }

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

类文章

public class Article {

    public String Name;
    public String Number;
    public int ImagesID;

    public Article(String Name, String Number, int ImagesID) {

        this.Name = Name;
        this.Number = Number;
        this.ImagesID = ImagesID;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        this.Name = Name;
    }
    public String getNumber() {
        return Number;
    }
    public void setNumber(String number) {
        this.Name = Number;
    }
    public int getImgID() {
        return ImagesID;
    }
    public void setImgID(int imgID) {
        this.ImagesID = ImagesID;
    }
}

类自定义适配器:

        class TIAdapter extends ArrayAdapter<Article> implements Filterable {
    private List<Article> articleList;
    private Context context;
    private Filter articleFilter;
    private List<Article> origArticleList;

    TIAdapter(List<Article> articleList, Context ctx) {
        super (ctx, R.layout.layout_text_image, articleList);
        this.articleList = articleList;
        this.context = ctx;
        this.origArticleList = articleList;
    }

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

    public Article getItem(int position) {
        return articleList.get(position);
    }

    public long getItemId(int position) {
        return articleList.get(position).hashCode();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ArticleHolder holder = new ArticleHolder();


        if (convertView == null) {
            // This a new view we inflate the new layout
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.layout_text_image, null);

            // Now we can fill the layout with the right values
            holder.textViewArtikel = (TextView) v.findViewById(R.id.textViewArtikel);
            holder.textViewArtikelNummer = (TextView) v.findViewById(R.id.textViewArtikelNummer);
            holder.imageViewArtikel = (ImageView) v.findViewById(R.id.imageViewArtikel);

            v.setTag(holder);
        }
        else {

            holder = (ArticleHolder) v.getTag();
            holder.imageViewArtikel = (ImageView) v.findViewById(R.id.imageViewArtikel);
            DecodeTask dt1 = (DecodeTask)holder.imageViewArtikel.getTag(R.id.imageViewArtikel);
            if(dt1 != null)
                dt1.cancel(true);
        }

        final Article n = articleList.get(position);

        holder.imageViewArtikel.setImageBitmap(null);
        DecodeTask dt2 = new DecodeTask(getContext(), holder.imageViewArtikel,  n.getImgID());
        dt2.execute();

        holder.textViewArtikel.setText(n.getName());
        holder.textViewArtikelNummer.setText(n.getNumber());
        holder.imageViewArtikel.setTag(n.getImgID(), dt2);
        return v;
    }

    public void resetData() {
        articleList = origArticleList;
    }

    private class ArticleHolder {
        TextView textViewArtikel;
        TextView textViewArtikelNummer;
        ImageView imageViewArtikel;
    }


    @Override
    public Filter getFilter() {
        if (articleFilter == null)
            articleFilter = new ArticleFilter();

        return articleFilter;
    }



    private class ArticleFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            // We implement here the filter logic
            if (constraint == null || constraint.length() == 0) {
                // No filter implemented we return all the list
                results.values = origArticleList;
                results.count = origArticleList.size();
            }
            else {
                // We perform filtering operation
                List<Article> nArticleList = new ArrayList<Article>();

                for (Article a : articleList) {
                    if (a.getName().toLowerCase().contains(constraint.toString().toLowerCase()))
                        nArticleList.add(a);
                }

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

            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {

            // Now we have to inform the adapter about the new list filtered
            if (results.count == 0)
                notifyDataSetInvalidated();
            else {
                articleList = (List<Article>) results.values;
                notifyDataSetChanged();
            }

        }

    }
}

    }
}
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ImageView imageView = null;

        if(row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.layout_text_image, parent, false);
            imageView = (ImageView)row.findViewById(R.id.imageViewArtikel);
        }
        else {
            imageView = (ImageView)row.findViewById(R.id.imageViewArtikel);
            DecodeTask dt1 = (DecodeTask)imageView.getTag(R.id.imageViewArtikel);
            if(dt1 != null)
                dt1.cancel(true);
        }
        imageView.setImageBitmap(null);
        DecodeTask dt2 = new DecodeTask(getContext(), imageView, ImagesID[position]);
        dt2.execute();

        TextView textViewArtikel = (TextView) row.findViewById(R.id.textViewArtikel);
        TextView textViewArtikelNummer = (TextView) row.findViewById(R.id.textViewArtikelNummer);

        imageView.setTag(R.id.imageViewArtikel, dt2);
        textViewArtikel.setText(Name[position]);
        textViewArtikelNummer.setText(Number[position]);
        return row;
    }
public class DecodeTask extends AsyncTask<String, Void, Bitmap> {
    Context mContext;
    ImageView v;
    int resId;

    public DecodeTask(Context context, ImageView iv, int res_id) {
        mContext = context;
        v = iv;
        resId = res_id;
    }
    protected Bitmap doInBackground(String... params) {
        return decodeBitmapFromResource(resId, 300, 300);
    }
    protected void onPostExecute(Bitmap result) {
        v.setImageBitmap(result);
    }
    private Bitmap decodeBitmapFromResource(int resId, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(mContext.getResources(), resId, options);
        options.inJustDecodeBounds = false;
        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), resId, options);
        return bmp;
    }

}

错误logcat:

05-03 10:56:43.922  28792-28792/com.kreussler.krapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.kreussler.krapp.c_DTArtikel_allforsearch$TIAdapter.getView(c_DTArtikel_allforsearch.java:286)
        at android.widget.AbsListView.obtainView(AbsListView.java)
        at android.widget.ListView.measureHeightOfChildren(ListView.java)
        at android.widget.ListView.onMeasure(ListView.java)
        at android.view.View.measure(View.java)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java)
        at android.view.View.measure(View.java)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java)
        at android.view.View.measure(View.java)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java)
        at android.view.View.measure(View.java)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java)
        at android.view.View.measure(View.java)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java)
        at android.view.Choreographer.doCallbacks(Choreographer.java)
        at android.view.Choreographer.doFrame(Choreographer.java)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java)
        at android.os.Handler.handleCallback(Handler.java)
        at android.os.Handler.dispatchMessage(Handler.java)
        at android.os.Looper.loop(Looper.java)
        at android.app.ActivityThread.main(ActivityThread.java)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
        at dalvik.system.NativeStart.main(Native Method)

共有1个答案

齐浩淼
2023-03-14

当我发现你的问题很有趣时,我用你的代码做了一个活动。我面临的最大问题是从哪里获得大约250幅图像。我首先想问你,但设法将306张图片的大小调整为100x100,并将它们放入可绘制文件夹。下面是更改后的getView()。

public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    ArticleHolder holder = new ArticleHolder();

    final Article n = articleList.get(position);

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.activity_sergej_lazy_res_listitem, null);

        holder.textViewArtikel       = (TextView)  v.findViewById(R.id.textViewArtikel);
        holder.textViewArtikelNummer = (TextView)  v.findViewById(R.id.textViewArtikelNummer);
        holder.imageViewArtikel      = (ImageView) v.findViewById(R.id.imageViewArtikel);

        v.setTag(holder);
    }
    else {

        holder = (ArticleHolder) v.getTag();
        DecodeTask dt1 = (DecodeTask)holder.imageViewArtikel.getTag( );
        if(dt1 != null)
          dt1.cancel(true);
      }


    holder.textViewArtikel.setText(n.getName());
    holder.textViewArtikelNummer.setText(n.getNumber());

    holder.imageViewArtikel.setImageBitmap(null);
    DecodeTask dt2 = new DecodeTask(getContext(), holder.imageViewArtikel, n.getImgID(), position ); 
    holder.imageViewArtikel.setTag(dt2);
    dt2.execute();

    return v;
}

由于使用了100x100的图像,因此不需要调整它们的大小。此处更改的AsyncTask:

public class DecodeTask extends AsyncTask<String, Void, Bitmap> {
Context mContext;
ImageView v;
int resId;
Bitmap bitmap = null;    
int position;

public DecodeTask(Context context, ImageView iv, int res_id, int _position ) { 
    mContext = context;
    v = iv;
    resId = res_id;
    position = _position;
    v.setTag( this); 
}

protected Bitmap doInBackground(String... params) {

  bitmap = BitmapFactory.decodeResource(mContext.getResources(), resId);

  return null;
}

protected void onPostExecute(Bitmap result) {

 if( position < ListViewLayout.getFirstVisiblePosition() || position > ListViewLayout.getLastVisiblePosition())
     return;

 if ( v.getTag() == this )
    v.setImageBitmap(bitmap);

 }

}

 类似资料:
  • 在自定义arrayAdapter中实现自定义getFilter时遇到问题。实际上,我不知道如何实现它。尝试了各种代码,但仍然没有成功。这是我的自定义阵列适配器。 这是ListTO课程。 这是布局图。 这里的搜索关键字来自“inputSearch”编辑文本。 这是文本更改的侦听器。 谢谢

  • 考虑到Spring数据存储库的自定义实现,我使用存储库上的带来所有HATEOAS生成的Goodnes: 现在,按照前面提到的文档,我已经用附加的简单方法创建了,用于介绍目的: 实施方式是: 我希望默认的SDR自动生成endpoint保持,只添加新的自定义方法/新的实现。我应该如何将这个自定义方法与spring-data REST/HATEOAS一起使用?使用简单的可以自动生成控制器endpoint

  • 我想实现定制的,它必须如下所示: 所以问题是: 如何实现自定义视图这样的按钮:只是一些图像

  • 我尝试开发一个小android应用程序,并显示一个对话框警报,其中只包含一个edittext,以填充自定义内容作为下一个链接 创建自定义布局我有这个代码,但它不工作 } 但是代码循环运行 我不明白 在我班上的主要活动 我有这个密码 这是我的风格。xml 我的logcat是下一个 谢谢你的帮助,

  • 问题内容: 我正在使用.NET的HttpClient向WebAPI发出请求,该WebAPI返回一些JSON数据,该数据需要在客户端进行一些自定义反序列化。为此,我已经完成了自己的工作,但是我不知道如何让该方法处理转换器的存在。 通过使用读取响应,然后将该字符串传递给,我已经解决了我的问题,但是似乎应该有一个更优雅的解决方案。 这是我的代码: 这是我所能做到的最好的,还是有一些更优雅的方法? 如果需

  • 我们正在使用spring和Spring-Security-3.2。最近,我们向RESTAPI添加了注释@preauthorize(以前是基于URL的)。 我们已经有了用-@ControllerAdvice和自定义的PermissionEvaluator注释的全局异常处理程序,除了错误消息之外,其他一切都正常工作。 是否可能抛出一个包含权限名称的异常,所以最终的错误消息应该是“Access Is d