Я пытаюсь добавить ProgressBar внизу списка при загрузке следующей страницы. Как это можно сделать? Есть ли способ разместить мой индикатор прогресса более эффективно? Я видел, что многие используют viewtype в адаптере, но я не понимаю, как он меняется. Кроме того, после завершения индикатора выполнения и добавления новой страницы я хочу, чтобы нижний элемент прокручивался на 1 позицию ниже.
Это мой list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:orientation="vertical"
android:divider="@android:color/black">
<TextView
android:id="@+id/id"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"/>
<TextView
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"/>
<TextView
android:id="@+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="10dp"/>
</LinearLayout>
<ProgressBar
android:visibility="gone"
android:id="@+id/progressbar"
android:progress="1"
android:layout_width="100dp"
android:layout_height="100dp"
android:indeterminate="true"
android:layout_gravity="center_horizontal"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ccc"/>
</android.support.v7.widget.CardView>
Это мой MyAdapter.java
import android.app.Activity;
import android.content.Context;
import android.service.autofill.Dataset;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.ArrayList;
import java.util.HashMap;
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
Context c;
ArrayList<String> id;
ArrayList<String> name;
ArrayList<String> email;
ArrayList<String> phone;
private Activity mactivity;
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private boolean isLoading;
private int visibleThreshold = 5;
private int lastVisibleItem, totalItemCount;
private OnLoadMoreListener onLoadMoreListener;
public interface OnLoadMoreListener {
void onLoadMore();
}
public MyAdapter(Context c, ArrayList<String> id, ArrayList<String> name, ArrayList<String> email, ArrayList<String> phone) {
this.c = c;
this.id = id;
this.name = name;
this.email= email;
this.phone = phone;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d("viewType", "onCreateViewHolder: "+viewType);
View v = LayoutInflater.from(c).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.id.setText(id.get(position));
holder.name.setText(name.get(position));
holder.email.setText(email.get(position));
holder.phone.setText(phone.get(position));
}
@Override
public int getItemCount() {
return id.size();
}
}
Это мой MainActivity.java
public class MainActivity extends AppCompatActivity {
private String URL = "myURL.php";
private String token = "mytoken";
RecyclerView mrecyclerView;
MyAdapter myAdapter;
ArrayList<String> id = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<String> email = new ArrayList<>();
ArrayList<String> phone = new ArrayList<>();
String next_page="";
ProgressBar mProgressBar;
private Parcelable recyclerViewState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar =(ProgressBar)findViewById(R.id.progressbar);
mrecyclerView = (RecyclerView) findViewById(R.id.mRecyclerview);
mrecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));
new getJSON().execute();
myAdapter = new MyAdapter(getApplicationContext(), id, name, email, phone);
mrecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
@Override
public void onLoadMore() {
if (URL != null) {
//mProgressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
recyclerViewState = mrecyclerView.getLayoutManager().onSaveInstanceState();
URL = next_page;
new getJSON().execute();
}
}, 200);
//mProgressBar.setVisibility(View.GONE);
}
}
});
}
private class getJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void v) {
super.onPostExecute(v);
mrecyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);
mrecyclerView.setAdapter(myAdapter);
}
@Override
protected Void doInBackground(Void... voids) {
HTTPHandler httpHandler = new HTTPHandler();
String json = httpHandler.makeCall(URL, token);
if (json != null) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("data");
next_page = String.valueOf(jsonObject.get("next_page_url"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
id.add(obj.getString("id"));
name.add(obj.getString("name"));
email.add(obj.getString("email"));
phone.add(obj.getString("phone"));
}
} catch (final JSONException e) {
Log.e("ERROR", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e("ERROR", "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
}
}
и я использовал EndlessRecyclerOnScrollListener.java из здесь
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
// public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();
/**
* The total number of items in the dataset after the last load
*/
private int mPreviousTotal=0;
/**
* True if we are still waiting for the last set of data to load.
*/
private boolean mLoading = true;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = recyclerView.getLayoutManager().getItemCount();
int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
}
}
int visibleThreshold = 5;
if (!mLoading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
onLoadMore();
mLoading = true;
}
}
public abstract void onLoadMore();
}