停止RecyclerView重新加载数据

时间:2018-03-31 19:00:00

标签: android android-recyclerview

我需要在向上滚动时停止RecyclerView重新加载数据,但我不知道如何 :( 我搜索它但我找不到任何答案

适配器: mPostAdapterNew

RecyclerView: MPostRV_new

那么你们可以帮助我吗?提前谢谢:D

编辑:这是我的代码:

    private void setupAdaptaterNew() {
    mPostAdapterNew = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
            Post.class,
            R.layout.item_layout_evenimente,
            PostViewHolder.class,
            mPostRef
    ) {

        @Override
        public void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
            final long EndZi = viewHolder.setEndZi(model.getEndZi());
            final int EndLuna = viewHolder.setEndLuna(model.getEndLuna());
            final int EndAn = viewHolder.setEndAn(model.getEndAn());
            Calendar cal = Calendar.getInstance();
            final Button btnAddEvent = viewHolder.itemView.findViewById(R.id.BtnParticip);
            final Button btnDeleteEvent = viewHolder.itemView.findViewById(R.id.BtnNuParticip);
            final int EndOra = viewHolder.setEndOra(model.getEndOra());
            final int EndMinute = viewHolder.setEndMinute(model.getEndMinute());
            final String headline = viewHolder.setHeadline(model.getHeadline());
            final String locatie = viewHolder.setStrada(model.getStrada());
            final String organizator = viewHolder.setOrganizator(model.getOrganizator());
            final String descriere = viewHolder.setPostDescriere(model.getDescriere());
            final ContentResolver cr = getActivity().getContentResolver();
            final ContentValues values = new ContentValues();
            final ContentResolver crReminder = getActivity().getContentResolver();
            final ContentValues valuesReminder = new ContentValues();
            final Uri event = null;
            final TextView nr_persoane = viewHolder.itemView.findViewById(R.id.nr_persoane);
            final String key = this.getRef(position).getKey();
            final Cursor data = mDatabaseHelper.getData();

            cal.set(Calendar.HOUR, 24);
            cal.set(Calendar.MINUTE, 59);
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.MONTH, EndLuna);
            cal.set(Calendar.DAY_OF_MONTH, (int) EndZi);
            cal.set(Calendar.YEAR, EndAn);


            if (Calendar.getInstance().before(cal)) {
                StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(model.getImageUrl());
                Glide.with(Fragment_events_new.this)
                        .using(new FirebaseImageLoader())
                        .load(storageReference)
                        .asBitmap()
                        .centerCrop()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                viewHolder.postIV.setImageBitmap(resource);
                            }
                        });


                viewHolder.setHeadline(model.getHeadline());
                viewHolder.setZiua(model.getZiua());
                viewHolder.setLuna(model.getLuna());
                viewHolder.setOra(model.getOra());
                viewHolder.setOrganizator(model.getOrganizator());
                viewHolder.setCategoria(model.getCategoria());
                viewHolder.setStrada(model.getStrada());
                viewHolder.setLocalitatea(model.getLocalitatea());
                viewHolder.setPostDescriere(model.getDescriere());
                viewHolder.setNrPersoane(model.getNrPeople());
            } else {
                viewHolder.itemView.setVisibility(View.GONE);
                viewHolder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0));
            }

            btnAddEvent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED ||
                            ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(getActivity(), "Permisii insuficiente.\n Va rugam sa activati permisiunea de CALENDAR", Toast.LENGTH_LONG).show();
                        NoPermissions();
                    } else {
                        addEvent(values, EndZi, EndAn, EndLuna, EndOra, EndMinute, headline, descriere, locatie, organizator, event, cr, valuesReminder, crReminder);
                        int i = viewHolder.setNrPersoane(model.getNrPeople()) + 1;
                        nr_persoane.setText(String.valueOf(i));
                        mPostRef.child(key).child("nrPeople").setValue(i);
                    }
                }
            });

            btnDeleteEvent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    deleteEvent(data, headline);
                    btnAddEvent.setVisibility(View.VISIBLE);
                    btnDeleteEvent.setVisibility(View.GONE);
                    int i = viewHolder.setNrPersoane(model.getNrPeople()) - 1;
                    nr_persoane.setText(String.valueOf(i));
                    mPostRef.child(key).child("nrPeople").setValue(i);
                }
            });

            if (CheckDB(headline)) {
                btnAddEvent.setVisibility(View.GONE);
                btnDeleteEvent.setVisibility(View.VISIBLE);
            } else {
                btnAddEvent.setVisibility(View.VISIBLE);
                btnDeleteEvent.setVisibility(View.GONE);
            }
        }
    };

}

@SuppressLint("MissingPermission")
private void addEvent(ContentValues values, float EndZi, int EndAn, int EndLuna, int EndOra, int EndMinute,
                      String headline, String descriere, String locatie, String organizator,
                      Uri event, ContentResolver cr, ContentValues valuesReminder, ContentResolver crReminder) {
    long startMillis = 0;
    long endMillis = 0;


    Calendar beginTime = Calendar.getInstance();
    beginTime.set(EndAn, EndLuna, (int) EndZi, EndOra, EndMinute);
    startMillis = beginTime.getTimeInMillis();
    Calendar endTime = Calendar.getInstance();
    endTime.set(EndAn, EndLuna, (int) EndZi, EndOra, EndMinute);
    endMillis = endTime.getTimeInMillis();
    //Add Values
    values.put(CalendarContract.Events.DTSTART, startMillis);
    values.put(CalendarContract.Events.TITLE, headline);
    values.put(CalendarContract.Events.DESCRIPTION, descriere); //TODO change description here!
    TimeZone timeZone = TimeZone.getDefault();
    values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
    values.put(CalendarContract.Events.CALENDAR_ID, 1);
    values.put(CalendarContract.Events.DTEND, endMillis);
    values.put(CalendarContract.Events.EVENT_LOCATION, locatie);
    values.put(CalendarContract.Events.ORGANIZER, organizator);
    event = cr.insert(CalendarContract.Events.CONTENT_URI, values);
    valuesReminder.put(CalendarContract.Reminders.DTSTART, startMillis);
    Uri REMINDERS_URI_DAY = Uri.parse(getCalendarUriBase(true) + "reminders");
    valuesReminder = new ContentValues();
    valuesReminder.put("event_id", Long.parseLong(event.getLastPathSegment()));
    valuesReminder.put("method", 1);
    valuesReminder.put("minutes", 1440);

    Uri uriReminderDay = crReminder.insert(REMINDERS_URI_DAY, valuesReminder);
    Uri REMINDERS_URI_HOUR = Uri.parse(getCalendarUriBase(true) + "reminders");
    valuesReminder = new ContentValues();
    valuesReminder.put("event_id", Long.parseLong(event.getLastPathSegment()));
    valuesReminder.put("method", 1);
    valuesReminder.put("minutes", 120);
    Uri uriReminder = crReminder.insert(REMINDERS_URI_HOUR, valuesReminder);

    createDialog(headline, "Ati adaugat evenimentul in calendar!");
    String event_id = String.valueOf(Long.parseLong(event.getLastPathSegment()));
    AddData(headline, event_id);
}

private void deleteEvent(Cursor data, String headline) {
    while (data.moveToNext()) {
        if (data.getString(1).equals(headline)) {
            Uri deleteUri = null;
            deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Long.parseLong(data.getString(2)));
            int rows = getActivity().getContentResolver().delete(deleteUri, null, null);
            createDialog(headline, "Ati sters evenimentu din calendar!");
            mDatabaseHelper.deleteData(headline, data.getString(2));

        }
    }
}

private boolean CheckDB(String headline) {
    Cursor data = mDatabaseHelper.getData();
    while (data.moveToNext()) {
        if (data.getString(1).equals(headline)) {
            return true;
        }
    }
    return false;
}

3 个答案:

答案 0 :(得分:1)

嗨,我在这里也遇到了同样的问题,特别是如果我要将像图像这样的中间内容加载到RecyclerView中时 使用一些大的缓存可以为您解决我的问题

MPostRV_new=view.findViewById(R.id.your_layout);
MPostRV_new.setHasFixedSize(true);
MPostRV_new.setLayoutManager(new LinearLayoutManager(getContext()));
MPostRV_new.setItemAnimator(null);
MPostRV_new.setItemViewCacheSize(50);

有关更多信息,请检查此资源 setItemViewCacheSize

答案 1 :(得分:0)

使用RecyclerView作为组件的意义在于,每次滚动时它都会重建可见项目,因此它会加载数据,您无法阻止&#34;它

您有两个选项:

  1. 检查您是否有长时间运行的操作(即,您每次查询网络或您的查看者具有大图像和复杂结构)。尝试优化它,例如从网络查询存储数据或调整图片大小

  2. 使用ListView。它会立即加载所有项目,然后如果您明确要求更新,那么它将更新。

答案 2 :(得分:0)

基本上你需要为你的循环视图适配器创建一个类(你应该使用recycleview而不是使用listview,因为它比listview更新,并且有许多listview没有的优化和新功能)。

MyRecyclerViewAdapter

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;

public MyRecyclerViewAdapter(Context context, List<FeedItem> feedItemList) {
    this.feedItemList = feedItemList;
    this.mContext = context;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
    CustomViewHolder viewHolder = new CustomViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
    FeedItem feedItem = feedItemList.get(i);

    //Render image using Picasso library
    if (!TextUtils.isEmpty(feedItem.getThumbnail())) {
        Picasso.with(mContext).load(feedItem.getThumbnail())
                .error(R.drawable.placeholder)
                .placeholder(R.drawable.placeholder)
                .into(customViewHolder.imageView);
    }

    //Setting text view title
    customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
}

@Override
public int getItemCount() {
    return (null != feedItemList ? feedItemList.size() : 0);
}

class CustomViewHolder extends RecyclerView.ViewHolder {
    protected ImageView imageView;
    protected TextView textView;

    public CustomViewHolder(View view) {
        super(view);
        this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
        this.textView = (TextView) view.findViewById(R.id.title);
    }
}

}

正如您在上面的示例中所看到的,所有项目都已被提取(准备显示而不是每次用户向上/向下滚动列表时都显示它们)。第二,有一些函数,比如onCreateViewHolder,你需要创建自己的视图持有者(给它增加一个布局,并从中创建一个持有者,它将保存所有用于显示你想要在列表中显示的数据的视图) 。第二个onBindViewHolder用于绑定(连接)持有者中的视图和适配器从其构造函数获取的数据。

实现适配器后,应按如下方式使用它: 你的活动/片段中的某个地方

...
List<FeedItem> data = manager.getItems();
MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(MainActivity.this, feedsList);
mRecyclerView.setAdapter(adapter);
...

这里有一些注意事项: 1)manager.getItems();是一个管理员,您可以从中获取您的项目,为了使用它您需要知道从哪里获得这些项目(网络/存储或其他来源)然后您需要实现它(有许多网站可以解释怎么做。 2)如果你正在使用片段,你应该使用而不是MainActivity.this getActivity()

您可以查看更多详情here

希望它能帮助您了解如何操作。