当我使用RecyclerView和Retrofit时如何加载更多?

时间:2017-08-31 04:51:28

标签: android android-recyclerview retrofit infinite-scroll endlessscroll

我想为一个网站开发Android应用程序。我阅读了来自json的网站帖子并在RecyclerView中每10个帖子显示一次,当用户在RecyclerView上滚动显示更多10个帖子并结束时! 我是业余爱好者,我写下面的代码,但我不知道在滚动到结束时显示更多数据并显示我的数据! (我想在任何页面中显示任何10个帖子)。 API链接:API_LINK

public NewAdapter(List<Doc> docs, int rowLayout, Context context) {
    this.docs = docs;
    this.rowLayout = rowLayout;
    this.context = context;
}

@Override
public NewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    v = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
    return new NewViewHolder(v);
}

@Override
public void onBindViewHolder(final NewViewHolder holder, final int position) {
    doc = docs.get(position);
    holder.tvTitle.setText(doc.getHeadline().getMain());
    holder.tvDate.setText(doc.getPubDate());
    holder.tvDescription.setText(doc.getSnippet());
    if (docs.get(position).getMultimedia().size() > 0) {
        Glide.with(context).load(url + doc.getMultimedia().get(0).getUrl())
                .thumbnail(0.5f)
                .placeholder(R.drawable.ic_close_black_24dp)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(R.drawable.ic_close_black_24dp)
                .into(holder.ivPoster);
    }
    holder.newLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            intent.putExtra("web_url", docs.get(position).getWebUrl());       
            context.startActivity(intent);
        }
    });
}

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

public class NewViewHolder extends RecyclerView.ViewHolder {
    LinearLayout newLayout;
    TextView tvTitle;
    TextView tvDescription;
    TextView tvDate;
    ImageView ivPoster;

    public NewViewHolder(View itemView) {
        super(itemView);
        newLayout = (LinearLayout) itemView.findViewById(R.id.new_layout);
        tvDate = (TextView) itemView.findViewById(R.id.tvDate);
        tvTitle = (TextView) itemView.findViewById(R.id.tvTitle);
        tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
        ivPoster = (ImageView) itemView.findViewById(R.id.ivPoster);
    }
}
  

MainActivity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    newDocs = (List<Doc>) getIntent().getSerializableExtra("Doc");
    change = getIntent().getBooleanExtra("change", false);
    init();
    setToolbar();
    setContent();

    //Xét điều kiện thay đổi
    if (change) {
        if (newDocs.size() > 0) {
            Toast.makeText(MainActivity.this, "Data", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Empty", Toast.LENGTH_SHORT).show();
        }
        setRecycleView(newDocs);
    }
    getData();


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

private void setToolbar() {
    setSupportActionBar(toolbar);
}

//Function xác nhận dữ liệu trả về id
private void init() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    mRecyclerView = (RecyclerView) findViewById(R.id.new_recycler_view);
    refreshLayout = (SwipeRefreshLayout) findViewById(R.id.srlMain);
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
}


private void setContent() {

    toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();
    navigationView.setNavigationItemSelectedListener(this);
    refreshLayout.setOnRefreshListener(this);

    //Set Recyclerview
    mRecyclerView.setNestedScrollingEnabled(false);
    final LinearLayoutManager mLayoutManager;
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));

}

    //Function lấy dữ liệu RecyclerView

private void setRecycleView(List<Doc> list) {
    newAdapter = new NewAdapter(list, R.layout.new_listitems, MainActivity.this);
    newAdapter.notifyDataSetChanged();
    mRecyclerView.setAdapter(newAdapter);

}

//Function nhận dữ liệu
private void getData() {
    APIinterface apiSevice = APIClient.getClient().create(APIinterface.class);
    Call<Resonpe> call = apiSevice.getHotNew(API_KEY);
    call.enqueue(new Callback<Resonpe>() {
        @Override
        public void onResponse(Call<Resonpe> call, Response<Resonpe> response) {
            if (response.isSuccessful()) {
                docs = response.body().getNewResponse().getDocs();
                if (!change) {
                    setRecycleView(docs);
                }
            } else {
                Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<Resonpe> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Internet is not connected", Toast.LENGTH_SHORT).show();
        }
    });
}

//Function tạo phần OptionMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    return super.onCreateOptionsMenu(menu);
}

//Function xử lý sự kiên click items của Option
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            refreshLayout.setRefreshing(false);
            if (change) {
                setRecycleView(newDocs);
            } else {
                setRecycleView(docs);
            }
        }
    }, 2500);

}

// Function xử lý sự kiên click items của NavigationView
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    newDocs = new ArrayList<>();
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if (id == R.id.nav_camera) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Sport")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_gallery) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Fashion")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_slideshow) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("Arts")) {
                newDocs.add(doc);
            }
        }
    } else if (id == R.id.nav_manage) {
        for (Doc doc : docs) {
            if (doc.getNewDesk().equals("None")) {
                newDocs.add(doc);
            }
        }
    }

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("Doc", (Serializable) newDocs);
    intent.putExtra("change", true);
    startActivity(intent);
    finish();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

1 个答案:

答案 0 :(得分:3)

您可以查看此代码路径教程。不使用任何外部库。只是一个班级。并且您可以在一个页面和页面中心定义所需的项目数,即5-6个项目,您可以加载更多数据并将notifyDatasetChange定义到Recycler视图适配器。请通过此链接。

https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView