繁体   English   中英

如何在没有单击的情况下从recyclerview适配器中删除所需的项目? 或从清单

[英]How to remove desired item from recyclerview adapter without Clicked ? or from List

我有天气API。 我已经为列表项设置了JSON对象,一切正常,并且在单击时将其从recycleradapter中删除了。

  public class ForecastAdapters extends RecyclerView.Adapter<ForecastAdapters.ForecastHolder> {

    private Context mContext;
    private List<OpenWeatherMapDaysTo> openWeatherMapDaysTos = new ArrayList<>();
    private OpenWeatherMapDaysTo mOpenWeatherMapDaysTo = new OpenWeatherMapDaysTo();
    private Toast mToast;
    private ForecastAdapters mForecastAdapters;


    public ForecastAdapters(Context context, List<OpenWeatherMapDaysTo> op) {
        mContext = context;
        openWeatherMapDaysTos = op;


    }


    public class ForecastHolder extends RecyclerView.ViewHolder {

        private TextView mTextName, mMornigText, mNightText,mClock;
        private ImageView mImage;

        public ForecastHolder(View view) {
            super(view);
            mTextName = (TextView) view.findViewById(R.id.fr_days_txt);
            mMornigText = (TextView) view.findViewById(R.id.fr_morning);
            mNightText = (TextView) view.findViewById(R.id.fr_night);
            mClock =(TextView)view.findViewById(R.id.fr_clock);
            mImage = (ImageView) view.findViewById(R.id.fr_imageView);


        }

        public void bindData(OpenWeatherMapDaysTo opData) {

            mTextName.setText(VolleyURL.getJustAllDate(opData.getList().get(getAdapterPosition()).getDt_txt()));
            mMornigText.setText(String.format("%d°C", Math.round(opData.getList().get(getAdapterPosition()).getMain().getTemp_max() - 273.15)));
            mNightText.setText(String.format("%d°C", Math.round(opData.getList().get(getAdapterPosition()).getMain().getTemp_min() - 273.15)));
            mClock.setText(String.format(VolleyURL.unixTimeStampToDateTime(opData.getList().get(getAdapterPosition()).getDt())));
            Picasso.with(mContext).load(VolleyURL.getImage(opData.getList().get(getAdapterPosition()).getWeather().get(0).getIcon())).into(mImage);

        }

    }


    @Override
    public ForecastAdapters.ForecastHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_fragment, parent, false);

        return new ForecastHolder(view);
    }

    @Override
    public void onBindViewHolder(final ForecastAdapters.ForecastHolder holder, final int position) {
        OpenWeatherMapDaysTo op = openWeatherMapDaysTos.get(position);
        holder.bindData(op);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mToast != null) {
                    mToast.cancel();
                }
                mToast = Toast.makeText(mContext, holder.getAdapterPosition()+ " Clicked", Toast.LENGTH_SHORT);
                mToast.show();
          /*      removeAt(holder.getAdapterPosition());*/

            }
        });

    }

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

    }

    public void removeAt(int position) {
        openWeatherMapDaysTos.remove(position);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position, openWeatherMapDaysTos.size());
    }


}

方法是这个

  public void removeAt(int position) {
    openWeatherMapDaysTos.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, openWeatherMapDaysTos.size());
}

我想删除不创建适配器时想要的JSON对象,或者创建适配器,然后删除不需要单击的项目,适配器将被更新并显示出来。 那怎么办 或任何想法。

例如,json包含星期一,星期二,星期三,星期四,星期五等。此外,它们是重复的,因为5天预报每3小时包含一次气象数据。 我无法删除三个星期一。

最后,这是我主要活动中的方法,我使用了Volley和gson。

UPDATE-1方法:(我更改了由两个For循环分隔的方法。)

  //get5daysForecast

public void getFiveDays() {
    mProg.setVisibility(View.VISIBLE);
    StringRequest mStringRequest = new StringRequest(Request.Method.POST, VolleyURL.API_GET_FORECAST, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            Gson gson = new Gson();

            Type mType = new TypeToken<OpenWeatherMapDays>() {
            }.getRawType();
            Type mTypeto = new TypeToken<OpenWeatherMapDaysTo>() {
            }.getType();
            openWeatherMapDays = gson.fromJson(response, mType);
            openWeatherMapDaysTo = gson.fromJson(response, mTypeto);

            for (int i = 0; i < openWeatherMapDays.getList().size(); i++) {

                String as = openWeatherMapDays.getList().get(i).getDt_txt();
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance(TimeZone.getTimeZone(as));
                c.add(Calendar.DAY_OF_YEAR, 2);
                String mTomorrow = sdf.format(c.getTime());


                Date dt = null;
                Date dtTomorrow = null;

                try {
                    dt = sdf.parse(as);

                    dtTomorrow = sdf.parse(mTomorrow);


                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

                String finalDate = dateFormat.format(dt);
                String tomorrow = dateFormat.format(dtTomorrow);


                if (finalDate.equals(tomorrow)) {


                    openWeatherMapDays.getList().get(i);
                    mOpenWeatherMapList.add(openWeatherMapDays);
                    mProg.setVisibility(View.INVISIBLE);
                    mCardUpView.setVisibility(View.VISIBLE);
                    mListUPview.setVisibility(View.VISIBLE);
                    mCardForecastAdapters.notifyDataSetChanged();
                }
            }

            for (int j = 0; j < openWeatherMapDaysTo.getList().size(); j++) {

                String as = openWeatherMapDaysTo.getList().get(j).getDt_txt();
                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance(TimeZone.getTimeZone(as));
                c.add(Calendar.DAY_OF_YEAR, 2);
                String mTomorrow = sdf.format(c.getTime());


                Date dt = null;
                Date dtTomorrow = null;

                try {
                    dt = sdf.parse(as);

                    dtTomorrow = sdf.parse(mTomorrow);


                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

                String finalDate = dateFormat.format(dt);
                String tomorrow = dateFormat.format(dtTomorrow);

                Log.d(TAG, "FinalDatewitVolley---------;> : " + finalDate.compareTo(VolleyURL.getDateNumber()));
                Log.d(TAG, "VolleyURL:-----------------------> " + VolleyURL.getDateNumber());
                Log.d(TAG, "FinalDate ----------------------->: " + finalDate);


                if ((finalDate.compareTo(VolleyURL.getDateNumber())!=0)) {

                    Log.d(TAG, "===TRUE====: ");
                    openWeatherMapDaysTo.getList().get(j);
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);
                    Log.d(TAG, "openWeatherDaysTo SIZE ===>  " + getmOpenWeatherMapListto.size());
                    mForecastAdapters = new ForecastAdapters(getApplicationContext(), getmOpenWeatherMapListto);
                    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
                    mRecyclerView.setLayoutManager(mLayoutManager);
                    mRecyclerView.setAdapter(mForecastAdapters);

                    mForecastAdapters.notifyDataSetChanged();


                }else {
                    Log.d(TAG, "===FALSE====: ");
                }


            }

        }


    }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    })

    {
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            int mStatusCode = response.statusCode;
            Log.d(TAG, "mStatusCode - FORECAST: " + mStatusCode);

            return super.parseNetworkResponse(response);
        }
    };
    mStringRequest.setRetryPolicy(new

            DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    VolleyController.getmInstance().

            addToRequestQueue(mStringRequest);

}

第二个适配器mCardForecastAdapter正在工作! 问题出在mForecastAdapters的“其他”情况下,我已经尝试过if(finalDate.compareTo(VolleyURL.getDateNumber())>0)但没有成功。

我将这些输出。

这个

如您所见,当compareTo()返回零时,列表中未包括在内。但是,RecyclerView显示了它。

另外:当我使用这种情况时:

if((finalDate.equals(VolleyURL.getDateNumber()))){
                    openWeatherMapDaysTo.getList().get(i);
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);
                    Log.d(TAG, "openWeatherDaysTo SIZE (2) ===>  " + getmOpenWeatherMapListto.size());}

RecyclerAdapter显示前5个项目,所有其他元素均未显示。但是我不想显示前5个元素,我想显示前5个元素之后。

编辑1:这是我的模型类和对象

 public class OpenWeatherMapDaysTo {

    private String cod;
    private double message;
    private int cnt;
    private List<Lists2> list;
    private City city;
    private Main main;

    public OpenWeatherMapDaysTo(){

    }

    public OpenWeatherMapDaysTo(String cod, double message, int cnt, List<Lists2> list, City city, Main main) {
        this.cod = cod;
        this.message = message;
        this.cnt = cnt;
        this.list = list;
        this.city = city;
        this.main = main;
    }

    public String getCod() {
        return cod;
    }

    public void setCod(String cod) {
        this.cod = cod;
    }

    public double getMessage() {
        return message;
    }

    public void setMessage(double message) {
        this.message = message;
    }

    public int getCnt() {
        return cnt;
    }

    public void setCnt(int cnt) {
        this.cnt = cnt;
    }

    public List<Lists2> getList() {
        return list;
    }

    public void setList(List<Lists2> list) {
        this.list = list;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }
}

我的lists2类:

  public class Lists2 {

    private int dt;
    private Main main;
    private List<Weather> weather;
    private Clouds clouds;
    private Wind wind;
    private Sys sys;
    private String dt_txt;

    public Lists2(int dt, Main main, List<Weather> weather, Clouds clouds, Wind wind, Sys sys, String dt_txt) {
        this.dt = dt;
        this.main = main;
        this.weather = weather;
        this.clouds = clouds;
        this.wind = wind;
        this.sys = sys;
        this.dt_txt = dt_txt;
    }

    public int getDt() {
        return dt;
    }

    public void setDt(int dt) {
        this.dt = dt;
    }

    public Main getMain() {
        return main;
    }

    public void setMain(Main main) {
        this.main = main;
    }

    public List<Weather> getWeather() {
        return weather;
    }

    public void setWeather(List<Weather> weather) {
        this.weather = weather;
    }

    public Clouds getClouds() {
        return clouds;
    }

    public void setClouds(Clouds clouds) {
        this.clouds = clouds;
    }

    public Wind getWind() {
        return wind;
    }

    public void setWind(Wind wind) {
        this.wind = wind;
    }

    public Sys getSys() {
        return sys;
    }

    public void setSys(Sys sys) {
        this.sys = sys;
    }

    public String getDt_txt() {
        return dt_txt;
    }

    public void setDt_txt(String dt_txt) {
        this.dt_txt = dt_txt;
    }
}

和另一个模型类

这些

最后:我的问题是

手机视图

编辑1:

据我所知,当您只想显示一个Lists2对象(每个RecyclerView项)时, List<Lists2>整个预测List<Lists2>List<Lists2> )发送到ForecastAdapters

您的for loop正在遍历Lists2对象,据我Lists2 ,这是一天中特定时间的预测。 这样,您应该创建一个ArrayListArrayList<Lists2> singleDays = new ArrayList<>(); )并将日期的每个第一个实例添加到singleDays for loop每次迭代中,检查openWeatherMapDaysTo.getList().get(j)对象是否已存在于singleDays 如果不存在,则将其添加到singleDays

为了使此代码更Lists2 ,您应该重写Lists2类的equals方法。 在覆盖的equals方法中,您检查日期是否相同,但不是一天中的时间。 您可以通过使用SimpleDateFormat来做到这一点,该SimpleDateFormat仅包含yyyy-MM-dd而不包含HH:mm:ss

public class Lists2 {
    ...

    @Override
    boolean equals(Object object) {
        if (object == null || !(object instanceof Lists2)) return false;

        Lists2 toCheck = (Lists2) object;

        String thisDateString = getDt_txt();
        String toCheckDateString = toCheck.getDt_txt();

        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date thisDate = sdf.parse(thisDateString);
        Date toCheckDate = sdf.parse(toCheckDateString);

        return thisDate.compareTo(toCheckDate) == 0;
    }
}

for loop完成对数据集的迭代之后,您可以创建ForecastAdapters并将其分配给RecyclerView

将您的getFiveDays()方法的第二个for loop更改为此

ArrayList<Lists2> singleDays = new ArrayList<>();

for (int j = 0; j < openWeatherMapDaysTo.getList().size(); j++) {
    if (!singleDays.contains(openWeatherMapDaysTo.getList().get(j))) {
        singleDays.add(openWeatherMapDaysTo.getList().get(j));
    }
}

mForecastAdapters = new ForecastAdapters(getApplicationContext(), singleDays);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mForecastAdapters);

同样,也不需要调用mForecastAdapters.notifyDataSetChanged(); 直接在创建适配器之后。

您还需要编辑ForecastsAdapter以使用Lists2而不是OpenWeatherMapDaysTo 在绑定数据的地方,无论如何都将获取Lists2的列表以填充视图,因此实际上您实际上仅在使用Lists2对象,但是您正在遍历所有预测的列表来获取它。


原始答案

所有这些都是基于我所做的假设,而没有看到名为OpenWeatherMapDaysOpenWeatherMapDaysTo的类。

看一下if语句中的代码。

Log.d(TAG, "===TRUE====: ");
openWeatherMapDaysTo.getList().get(j); // line 1
getmOpenWeatherMapListto.add(openWeatherMapDaysTo); // line 2

在第1行上,您正在调用get(j) ,但未将其分配给任何东西。 我假设这是您想要在RecyclerView显示的项目。

在第2行上,您将整个openWeatherMapDaysTo对象(包含不需要的天数列表)添加到getmOpenWeatherMapListto ArrayList (我假设它是ArrayList )。 因此,我认为正在发生的事情是,即使您不包括这些先前的项目(基于compareTo检查),它们也将与整个openWeatherMapDaysTo对象一起添加。

我想你想做的是

getmOpenWeatherMapListto.add(openWeatherMapDaysTo.getList().get(j));

根据j计数器添加单日(在您的示例“ 2017年10月24日”中)。

还要在第一个for loop检查if语句。 您调用get(i) ,但不要将其分配给任何东西。

您可能还想添加break; 在执行TRUE代码块后退出for loop ,以防止重新创建并重新设置ForecastAdapters

这是我认为您的第二个for loop if语句应该看起来像的样子(如果我理解您的代码并且您正在尝试完成):

if ((finalDate.compareTo(VolleyURL.getDateNumber())!=0)) {
    Log.d(TAG, "===TRUE====: ");

    getmOpenWeatherMapListto.add(openWeatherMapDaysTo.getList().get(j));

    Log.d(TAG, "openWeatherDaysTo SIZE ===>  " + getmOpenWeatherMapListto.size());

    mForecastAdapters = new ForecastAdapters(getApplicationContext(), getmOpenWeatherMapListto);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mForecastAdapters);
    mForecastAdapters.notifyDataSetChanged();

    // break out of the for loop here otherwise your adapter will be created
    // again and set to your recyclerview
    break;
}

我在Volley Request中编写了此代码,此问题已解决。

 for (int j = 0; j < openWeatherMapDaysTo.getList().size(); j++) {

                DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_YEAR, 0);
                String mNowDay = sdf.format(c.getTime());
                Date dtNow = null;

                Calendar cT = Calendar.getInstance();
                cT.add(Calendar.DAY_OF_YEAR, 1);
                String mTomorrow = sdf.format(cT.getTime());

                Date dtTomorrow = null;

                try {
                    dtNow = sdf.parse(mNowDay);
                    dtTomorrow = sdf.parse(mTomorrow);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                String finalDate = dateFormat.format(dtNow);
                String finalTomorrow = dateFormat.format(dtTomorrow);

                Log.d(TAG, "JSON ----------------------->: " + VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()));
                Log.d(TAG, "VolleyURL.getDateNumber----------------------->: " + VolleyURL.getDateNumber());
                Log.d(TAG, "FINALDATE ---------> : " + finalDate);
                Log.d(TAG, "IF IC ---------> : " + VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()));

                if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 12:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");


                    openWeatherMapDaysTo.getList().remove(j);
                    j--;


                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 15:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;

                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 18:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;

                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalDate + " 21:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalTomorrow + " 00:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else if (VolleyURL.unixTimeStampToDateTime(openWeatherMapDaysTo.getList().get(j).getDt()).equals(finalTomorrow + " 03:00")) {
                    Log.d(TAG, " \n ===TRUE====: ");
                    openWeatherMapDaysTo.getList().remove(j);
                    j--;
                } else {
                    Log.d(TAG, " \n ===FALSE====: ");
                    getmOpenWeatherMapListto.add(openWeatherMapDaysTo);


                }

我不能将else-if语句转换为switch-case语句。但是现在它可以正常工作了。 如果您有关于此问题的建议(与陈述的转换有关),我将很高兴听到。

截图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM