我正在使用recyclerview,我想使用json从服务器获取更多数据。 场景是这样的: - 在第一次点击时,我想在列表中显示5个页面,并且当用户点击第二次点击显示更多按钮时,在Recyclerview下方显示更多按钮5个页面。我可以这样做吗
这是我的init():
public void init() {
mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);
mProgressBar.setVisibility(View.GONE);
m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more);
m_showMore.setBackgroundColor(Color.TRANSPARENT);
m_showMore.setVisibility(View.GONE);
// Getting the string array from strings.xml
m_n_FormImage = new int[]{
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview
m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview
m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview
mLayoutManager = new LinearLayoutManager(getActivity());
m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count...
m_Handler = new Handler();
}
public void implementScroll() {// on scroll load more data from server.............
m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
m_showMore.setVisibility(View.VISIBLE);
m_showMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//change boolean value
m_showMore.setVisibility(View.GONE);
m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5;// increment of record count by 5 on next load data
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string /////
new DealNext().execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA......
}
});
} else {
m_showMore.setVisibility(View.GONE);
}
}
});
}
这是我的第一个serevr热门: -
//sending deal data to retreive response from server
public String DealListing(String url, CRegistrationDataStorage login) {
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("recordcount", sz_RecordCount);
jsonObject.put("lastcountvalue", sz_LastCount);
//jsonObject.put("emailId", "nirajk1190@gmail.com");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.println("InputStream....:" + inputStream.toString());
System.out.println("Response....:" + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.println("statusLine......:" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null)
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul.....:" + s_szresult);
// 11. return s_szResult
return s_szresult;
}
public void getResponse() throws JSONException {// getting response from serevr ..................
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {// server based condition
m_oAdapter = new CDealAppListingAdapter(s_oDataset);// create adapter object and add arraylist to adapter
m_oAdapter.notifyDataSetChanged();
m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions
CToastMessage.getInstance().showToast(getActivity(), "Connection not avaliable");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions .....
CToastMessage.getInstance().showToast(getActivity(), "No More Deals Available");
}
}
// sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask<String, Void, String> {
public CRegistrationDataStorage oRegisterStorage;
public CDealAppDatastorage item;
@Override
protected void onPreExecute() {
super.onPreExecute();
CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Loading Deals...");
}
@Override
protected String doInBackground(String... urls) {
return DealListing(urls[0], oRegisterStorage);// sending data to server...
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(final String result) {
new Thread(new Runnable() {
@Override
public void run() {
m_Handler.post(new Runnable() {
@Override
public void run() {
CProgressBar.getInstance().hideProgressBar();// hide progress bar after getting response from server.......
try {
m_oResponseobject = new JSONObject(result);// getting response from server
JSONArray posts = m_oResponseobject.optJSONArray("dealList");
s_oDataset = new ArrayList<CDealAppDatastorage>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
}
这是我的第二个serevr点击
// sending data and receive reponse on second hit T LOAD MORE DATA when show more Btn clicked..............
private class DealNext extends AsyncTask<String, Void, String> {
public CRegistrationDataStorage oRegisterStorage;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR
}
@Override
protected String doInBackground(String... urls) {
//My Background tasks are written here
synchronized (this) {
return DealListing(urls[0], oRegisterStorage);// POST DATA TO SERVER
}
}
@Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
new Thread(new Runnable() {
@Override
public void run() {
m_Handler.post(new Runnable() {
@Override
public void run() {
mProgressBar.setVisibility(View.INVISIBLE);// DISMISS PROGRESS BAR..........
try {
m_oResponseobject = new JSONObject(result);// getting response from server
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_n_Image(m_n_FormImage[i]);// static image for testing purpose not original....
s_oDataset.add(item);// add items to arraylist....
m_oAdapter.notifyItemInserted(s_oDataset.size());// notify adapter when deal added to recylerview
}
getResponse();// getting response from server.....and also here response based logics...
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
}
这是我的适配器类:
public class CDealAppListingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static CDealAppDatastorage list;
private static ArrayList<CDealAppDatastorage> s_oDataset;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> mDataList) {
s_oDataset = mDataList;
}
@Override
public int getItemViewType(int position) {
return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
if (i == VIEW_TYPE_ITEM) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false);
return new DealAppViewHolder(view);
} else if (i == VIEW_TYPE_LOADING) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false);
return new LoadingViewHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DealAppViewHolder) {
list = s_oDataset.get(position);// receiving item on position on index i
DealAppViewHolder dealAppViewHolder = (DealAppViewHolder) holder;
dealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image());
dealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText());
dealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText());
} else if (holder instanceof LoadingViewHolder) {
LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
loadingViewHolder.progressBar.setIndeterminate(true);
}
}
@Override
public int getItemCount() {
return (s_oDataset == null ? 0 : s_oDataset.size());//counting size of odata in ArrayList
}
static class LoadingViewHolder extends RecyclerView.ViewHolder {
public ProgressBar progressBar;
public LoadingViewHolder(View itemView) {
super(itemView);
progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
}
}
public static class DealAppViewHolder extends RecyclerView.ViewHolder {
public static ImageView s_szAppImage;
public static TextView s_szheadingText, s_szSubHeader;
public static Button s_szGetDealBtn;
public DealAppViewHolder(View itemLayoutView) {
super(itemLayoutView);
s_szheadingText = (TextView) itemLayoutView.findViewById(R.id.headingText);// finding id of headerText...
s_szSubHeader = (TextView) itemLayoutView.findViewById(R.id.subHeaderText);// finding id of subHeader.....
s_szAppImage = (ImageView) itemLayoutView.findViewById(R.id.appImage);//finding Id of Imgae in CardView
s_szGetDealBtn = (Button) itemLayoutView.findViewById(R.id.getDealBtn);// finding id of getdeal Btn
Random rnd = new Random();//creating object of Random class
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));//genrating random color
s_szGetDealBtn.setBackgroundColor(color);//backgraound color of getDeal Btn
s_szGetDealBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
@Override
public void onClick(View v) {//send to deal detail page onclick getDeal Btn
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra("DealCode", s_oDataset.get(getPosition()).getM_szsubHeaderText());
i.putExtra("headerText", s_oDataset.get(getPosition()).getM_szHeaderText());
v.getContext().startActivity(i);
}
});
itemLayoutView.setOnClickListener(new View.OnClickListener() {// onclick cardview
@Override
public void onClick(View v) {// onclick cardview send to deal app listing details page .....
Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
i.putExtra("DealCode", list.getM_szsubHeaderText());
i.putExtra("headerText", list.getM_szHeaderText());
v.getContext().startActivity(i);
}
});
}
}
}
答案 0 :(得分:0)
在适配器中存储两个列表,当前显示的列表和完整列表,或者只获取API允许的内容。
然后,您可以将getItemCount
中的适配器大小设置为显示的列表大小+ 1(用于查看更多项目)。您需要添加一个单独的视图类型以在getItemViewType
中返回以查看更多单元格(如果当前位置显示列表大小,则显示它的逻辑)。您还需要为加载更多单元格添加新视图和视图持有者。
在您设置了新视图后,您只需添加一个点击监听器,如果点击,则将完整列表中的5个项目添加到当前显示的列表中(确保从当前显示的列表开始) - 完整列表的1个索引,并致电notifyDataSetChanged
或notifyItemAdded
x 5。
抱歉,我目前没有时间为您编写适当的适配器,但我希望上述解释就足够了。