如果没有结果则显示吐司

时间:2018-01-20 04:56:45

标签: java android

我正在使用过滤SearchView。一切正常但是,如果没有结果,我想要秀吐司..

怎么办?谢谢

我已在下面发布了我的代码,所以任何帮助都会很棒......

我没有在那里放任何代码,因为我不知道如何显示"没有找到任何结果"

CustomFilter.java

 public CustomFilter(ArrayList<Player> filterList, MyAdapter adapter)
    {
        this.adapter=adapter;
        this.filterList=filterList;

    }

    //FILTERING OCURS
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results=new FilterResults();

        //CHECK CONSTRAINT VALIDITY
        if(constraint != null && constraint.length() > 0)
        {
            //CHANGE TO UPPER
            constraint=constraint.toString().toUpperCase();
            //STORE OUR FILTERED PLAYERS
            ArrayList<Player> filteredPlayers=new ArrayList<>();

            for (int i=0;i<filterList.size();i++)
            {
                //CHECK
                if(filterList.get(i).getName().toUpperCase().contains(constraint))
                {
                    //ADD PLAYER TO FILTERED PLAYERS
                    filteredPlayers.add(filterList.get(i));
                }
            }

            results.count=filteredPlayers.size();
            results.values=filteredPlayers;
        }else
        {
            results.count=filterList.size();
            results.values=filterList;

        }


        return results;
    }

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

       adapter.players= (ArrayList<Player>) results.values;

        //REFRESH
        adapter.notifyDataSetChanged();
    }
}

myadapter.java

  @Override
    public int getItemCount() {
        return players.size();
    }

    //RETURN FILTER OBJ
    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new CustomFilter(filterList, this);
        }

        return filter;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以在代码中添加以下找不到任何结果的行。

Toast.makeText(context, text, duration).show();

您可以获得如下所示的上下文对象,

Context context = getApplicationContext();

text是您要显示的任何字符串/消息,如&#34;未找到结果&#34;

CharSequence text = "No Results found";

duration您可以设置为Toast.LENGTH_LONG

答案 1 :(得分:0)

首先,在Context mcontext中声明CustomFilter.java变量,然后在构造函数中接受上下文

Context mcontext;
    public CustomFilter(ArrayList<Player> filterList, MyAdapter adapter, Context con)
        {
            this.adapter=adapter;
            this.filterList=filterList;
            this.mcontext=con;
        }

publishResults方法上检查结果计数是否为0。

如果是0则显示这样的祝酒词。

if(results.count==0)
{
 Toast.makeText(mcontext, "No results...", Toast.LENGTH_SHORT).show();
}

else
{

adapter.players= (ArrayList<Player>) results.values; 
adapter.notifyDataSetChanged();

}