- >以下是包含recyclerview的Activity代码我已经完成了以下代码 这是MainActivity的代码
public class MainActivity extends AppCompatActivity implements
PaginationAdapterCallback,StoryAdapter.OnClickImageListener{
@Bind(R.id.drawer_layout)
DrawerLayout drawer_layout;
@Bind(R.id.drawer)
ImageView ivDrawer;
@Bind(R.id.imgHome)
ImageView imgHome;
@Bind(R.id.imgFriendRequest)
FrameLayout imgFriendRequest;
@Bind(R.id.imgTimeline)
ImageView imgTimeline;
@Bind(R.id.drawerListView)
ListView drawerListView;
@Bind(R.id.etSearch)
TextView etSearch;
@Bind(R.id.nestedScroll)
ScrollView scroll;
@Bind(R.id.imgGallery)
ImageView imgGallery;
@Bind(R.id.imgNotification)
FrameLayout imgNotification;
@Bind(R.id.imgChat)
FrameLayout imgChat;
@Bind(R.id.error_btn_retry)
Button error_btn_retry;
@Bind(R.id.gestureImg)
ImageView gestureImg;
SwipeRefreshLayout swiperefresh;
@Bind(R.id.rvHairList)
RecyclerView rvPostList;
@Bind(R.id.rvStoryList)
RecyclerView rvStoryList;
@Bind(R.id.progressBar1)
ProgressBar pb;
@Bind(R.id.main_progress)
ProgressBar progressBar;
@Bind(R.id.llDrawer)
LinearLayout llDrawer;
static TextView notiCount;
static TextView msgCount;
static ImageView imgNoti;
static ImageView imgMsg;
static TextView friendCount;
static ImageView imgFnd;
private PostAdapter postAdapter;
private StoryAdapter storyAdapter;
@Bind(R.id.mainLayout)
LinearLayout mainLayout;
@Bind(R.id.error_layout)
LinearLayout errorLayout;
@Bind(R.id.error_txt_cause)
TextView txtError;
private ActionBarDrawerToggle actionBarDrawerToggle;
private LinearLayoutManager linearlayoutManager;
private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 218;
private List<MediaItem> mMediaSelectedList;
private static int SPLASH_TIME_OUT = 3000;
private static int SELECT_IMAGE = 1;
String req, status, text, tagId,tagdId, imagePath, fcmid;
private static final String TAG = "MainActivity";
static String id;
protected Handler handler;
public static boolean mboolean = false;
private boolean isLastPage = false;
private int TOTAL_PAGES ;
private int currentPage = PAGE_START;
private static final int PAGE_START = 1;
long totalSize = 0;
private boolean isLoading = false;
private AllPostService movieService;
static Uri defaultSoundUri;
static Ringtone r;
private static final int SELECT_PICTURE = 101;
private String selectedImagePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
rvPostList.setNestedScrollingEnabled(false);
swiperefresh = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
friendCount = (TextView) findViewById(R.id.friendCount);
imgNoti = (ImageView) findViewById(R.id.imgNoti);
imgFnd = (ImageView) findViewById(R.id.imgFnd);
imgMsg = (ImageView) findViewById(R.id.imgMsg);
notiCount = (TextView) findViewById(R.id.notiCount);
msgCount = (TextView) findViewById(R.id.msgCount);
storyAdapter=new StoryAdapter(this);
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
rvStoryList.setLayoutManager(horizontalLayoutManager);
rvStoryList.setAdapter(storyAdapter);
initDrawer();
init();
swiperefresh.setOnRefreshListener(new
SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshContent();
}
});
}
private void init() {
isLoading=true;
postAdapter = new PostAdapter(this);
linearlayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
rvPostList.setLayoutManager(linearlayoutManager);
rvPostList.setItemAnimator(new DefaultItemAnimator());
rvPostList.setAdapter(postAdapter);
movieService = AllPostApi.getClient().create(AllPostService.class);
loadFirstPage();
setScrollListener();
}
private int mTotalScrolled = 0;
int pastVisiblesItems, visibleItemCount, totalItemCount;
private void setScrollListener(){
rvPostList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
mTotalScrolled += dy;
int topRowVerticalPosition =
(recyclerView == null || recyclerView.getChildCount() ==
0) ? 0 : recyclerView.getChildAt(0).getTop();
swiperefresh.setEnabled(topRowVerticalPosition >= 0);
if (dy > 0) //check for scroll down
{
visibleItemCount = linearlayoutManager.getChildCount();
totalItemCount = linearlayoutManager.getItemCount();
pastVisiblesItems = linearlayoutManager.findFirstVisibleItemPosition();
if (!isLoading && !isLastPage) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
isLoading = true;
currentPage += 1;
loadNextPage();
}
}
}
}
});
}
private Call<Post> callTopRatedMoviesApi() {
return movieService.getTopRatedMovies(
id,
currentPage
);
}
private void loadFirstPage() {
Log.d(TAG, "loadFirstPage: ");
// To ensure list is visible when retry button in error view is clicked
hideErrorView();
callTopRatedMoviesApi().enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
hideErrorView();
List<Result> results = fetchResults(response);
progressBar.setVisibility(View.GONE);
if(results.size() > 0){
postAdapter.addFirtTime(results);
}
if (currentPage < TOTAL_PAGES) postAdapter.addLoadingFooter();
else isLastPage = true;
isLoading=false;
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
t.printStackTrace();
showErrorView(t);
}
});
}
private void showErrorView(Throwable throwable) {
if (errorLayout.getVisibility() == View.GONE) {
errorLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
txtError.setText(fetchErrorMessage(throwable));
}
}
private String fetchErrorMessage(Throwable throwable) {
String errorMsg = getResources().getString(R.string.error_msg_unknown);
if (!isNetworkConnected()) {
errorMsg = getResources().getString(R.string.error_msg_no_internet);
} else if (throwable instanceof TimeoutException) {
errorMsg = getResources().getString(R.string.error_msg_timeout);
}
return errorMsg;
}
private void hideErrorView() {
if (errorLayout.getVisibility() == View.VISIBLE) {
errorLayout.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
private List<Result> fetchResults(Response<Post> response) {
Post topRatedMovies = response.body();
TOTAL_PAGES = (int) topRatedMovies.count_page;
return topRatedMovies.friendList;
}
private void loadNextPage() {
if (currentPage > TOTAL_PAGES)
{
isLastPage = true;
return;
}
Log.d(TAG, "loadNextPage: " + currentPage);
callTopRatedMoviesApi().enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
postAdapter.removeLoadingFooter();
isLoading = false;
List<Result> results = fetchResults(response);
if(results.size() > 0) {
postAdapter.addAll(results);
}
if (currentPage != TOTAL_PAGES)
postAdapter.addLoadingFooter();
else {
isLastPage = true;
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
t.printStackTrace();
postAdapter.showRetry(true, fetchErrorMessage(t));
if(currentPage>0)
currentPage--;
}
});
}
private void refreshContent(){
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
currentPage = 1;
isLoading=true;
isLastPage=false;
movieService =
AllPostApi.getClient().create(AllPostService.class);
loadFirstPage();
swiperefresh.setRefreshing(false);
}
},SPLASH_TIME_OUT);
}
@OnClick(R.id.error_btn_retry)
public void Onerror_btn_retryClick() {
if(isNetworkConnected()){
currentPage = 1;
isLoading=true;
isLastPage=false;
movieService = AllPostApi.getClient().create(AllPostService.class);
loadFirstPage();
}else {
}
}
@OnClick(R.id.llHome)
public void OnHomeClick() {
scroll.smoothScrollTo(0,0);
}
}
在适用于使用
的recyclerview的适配器下方 public class PostAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Activity activity;
private static final int ITEM = 0;
private static final int LOADING = 1;
private List<Result> movieResults;
private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;
String id;
private String errorMsg;
private int pos = 0;
long countvalue;
private PaginationAdapterCallback mCallback;
PostHolder postHolder;
public PostAdapter(Activity activity) {
this.activity = activity;
this.mCallback = (PaginationAdapterCallback) activity;
movieResults = new ArrayList<>();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
@NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent,
LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View v1 = inflater.inflate(R.layout.item_post, parent, false);
viewHolder = new PostHolder(v1);
return viewHolder;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final Result result = movieResults.get(position);
id = Utils.getPref(activity,"rid","");
switch (getItemViewType(position)) {
case ITEM:
final PostHolder movieVH = (PostHolder) holder;
postHolder = movieVH;
if(pos == position){
movieVH.adView.setVisibility(View.VISIBLE);
AdRequest re= new AdRequest.Builder()
.build();
movieVH.adView.loadAd(re);
}else{
movieVH.adView.setVisibility(View.GONE);
}
if(result.likeCount > 0){
movieVH.likeCount.setVisibility(View.VISIBLE);
movieVH.likeCount.setText(result.likeCount+" Likes");
}else {
movieVH.likeCount.setVisibility(View.GONE);
}
Log.e("position null",position+"");
if(result.likeStatus.equals("Like")){
movieVH.imgLike.setVisibility(View.VISIBLE);
movieVH.imgLike.setChecked(true);
}else {
movieVH.imgLike.setChecked(false);
}
movieVH.imgLike.setTag(movieVH);
movieVH.imgLike.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CallForAddLike(result.postid,result.sharid,
result.rid, v,position);
}
});
if(result.commentCount> 0){
movieVH.commentCount.setVisibility(View.VISIBLE);
movieVH.commentCount.setText(result.commentCount+"
Comments");
}else {
movieVH.commentCount.setVisibility(View.GONE);
}
if(result.shareCount > 0){
movieVH.shareCount.setVisibility(View.VISIBLE);
movieVH.shareCount.setText(result.shareCount+" Shares");
}else {
movieVH.shareCount.setVisibility(View.GONE);
}
movieVH.postedTime.setText(result.dateTime);
movieVH.imgComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(activity,CommentActivity.class);
i.putExtra("postid",result.postid);
i.putExtra("shareid",result.sharid);
i.putExtra("receiver",result.rid);
activity.startActivity(i);
}
});
Glide.with(activity)
.load(result.path)
.listener(new RequestListener<String, GlideDrawable>() {
@Override
public boolean onException(Exception e, String
model, Target<GlideDrawable> target, boolean isFirstResource) {
movieVH.progress.setVisibility(View.GONE);
return false;
}
@Override
public boolean onResourceReady(GlideDrawable
resource, String model, Target<GlideDrawable> target, boolean
isFromMemoryCache, boolean isFirstResource) {
movieVH.progress.setVisibility(View.GONE);
return false;
}
})
.into(movieVH.postedImg);
Picasso.with(activity)
.load(result.profilePicture)
.placeholder(R.drawable.loader)
.into(movieVH.userPic);
if(result.message.equals("")){
movieVH.postedMsg.setVisibility(View.INVISIBLE);
}else {
movieVH.postedMsg.setVisibility(View.VISIBLE);
movieVH.postedMsg.setText(result.message);
}
if(result.poststatus.length() == 0){
movieVH.userName.setText(result.fname+" "+
result.lname);
}else {
String CurrentString = result.poststatus;
String[] separated = CurrentString.split(",");
if(separated.length>1){
movieVH.userName.setText(Html.fromHtml(
result.fname+" "+result.lname +
"<font color=\"#ADACAB\">" +
" with " +
"</font>" + separated[0]+"<font color=\"#ADACAB\">" + " and " + "</font>"
+String.valueOf(separated.length-1)+" others "));
}else {
movieVH.userName.setText(Html.fromHtml(result.fname+" "+
result.lname +"<font color=\"#ADACAB\">" +
" with " +
"</font>" + separated[0] ));
}
}
if(id.equals(result.rid)){
movieVH.dltPost.setVisibility(View.VISIBLE);
}else {
movieVH.dltPost.setVisibility(View.INVISIBLE);
}
movieVH.commentCount.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(activity, CommentList.class);
i.putExtra("shareid",result.sharid);
activity.startActivity(i);
}
});
movieVH.likeCount.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Intent i = new Intent(activity, LikeActivity.class);
i.putExtra("shareId",result.sharid);
activity.startActivity(i);
}
});
break;
case LOADING:
LoadingVH loadingVH = (LoadingVH) holder;
if (retryPageLoad) {
loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
loadingVH.mProgressBar.setVisibility(View.GONE);
loadingVH.mErrorTxt.setText(errorMsg != null ? errorMsg :
activity.getString(R.string.error_msg_unknown));
} else {
loadingVH.mErrorLayout.setVisibility(View.GONE);
loadingVH.mProgressBar.setVisibility(View.VISIBLE);
}
break;
}
}
public void removeAt(int position) {
movieResults.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, movieResults.size());
}
@Override
public int getItemViewType(int position) {
return (position == movieResults.size() - 1 && isLoadingAdded) ? LOADING
: ITEM;
}
@Override
public int getItemCount() {
return movieResults == null ? 0 : movieResults.size();
}
public void addAll(List<Result> moveResults) {
final int pos=movieResults.size();
movieResults.addAll(moveResults);
notifyItemRangeInserted(pos,moveResults.size());
}
public void cleardata() {
movieResults.clear();
movieResults=new ArrayList<>();
}
public void remove(Result r) {
int position = movieResults.indexOf(r);
if (position > -1) {
movieResults.remove(position);
notifyItemRemoved(position);
}
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public void addFirtTime(List<Result> moveResults) {
movieResults.clear();
movieResults=new ArrayList<>();
movieResults.addAll(moveResults);
notifyDataSetChanged();
}
public void addLoadingFooter() {
isLoadingAdded = true;
add(new Result());
}
public void removeLoadingFooter() {
isLoadingAdded = false;
int position = movieResults.size() - 1;
Result result = getItem(position);
if (result != null) {
movieResults.remove(position);
notifyItemRemoved(position);
}
}
public Result getItem(int position) {
return movieResults.get(position);
}
public void add(Result r) {
movieResults.add(r);
notifyItemInserted(movieResults.size()-1);
}
protected class LoadingVH extends RecyclerView.ViewHolder implements
View.OnClickListener {
private ProgressBar mProgressBar;
private ImageButton mRetryBtn;
private TextView mErrorTxt;
private LinearLayout mErrorLayout;
public LoadingVH(View itemView) {
super(itemView);
mProgressBar = (ProgressBar)
itemView.findViewById(R.id.loadmore_progress);
mRetryBtn = (ImageButton)
itemView.findViewById(R.id.loadmore_retry);
mErrorTxt = (TextView)
itemView.findViewById(R.id.loadmore_errortxt);
mErrorLayout = (LinearLayout)
itemView.findViewById(R.id.loadmore_errorlayout);
mRetryBtn.setOnClickListener(this);
mErrorLayout.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.loadmore_retry:
case R.id.loadmore_errorlayout:
showRetry(false, null);
mCallback.retryPageLoad();
break;
}
}
}
public void showRetry(boolean show, @Nullable String errorMsg) {
retryPageLoad = show;
notifyItemChanged(movieResults.size() - 1);
if (errorMsg != null) this.errorMsg = errorMsg;
}
private void CallForAddLike(final String postId, final String shareId, final String receiverId,
final View holder, final int position) {
new Handler(Looper.myLooper()).post(new Runnable() {
@Override
public void run() {
try {
RequestParams params = new RequestParams();
params.put(RequestParamsUtils.U_ID, id);
params.put(RequestParamsUtils.POST_ID, postId);
params.put(RequestParamsUtils.SHARE_ID, shareId);
params.put(RequestParamsUtils.RECEIVER, receiverId);
Debug.e("sent parameters", params.toString());
AsyncHttpClient clientPhotos = AsyncHttpRequest.newRequest();
clientPhotos.post(new URLs().ADD_LIKE, params, new ResponseHandler(activity,
holder,position));
} catch (Exception e) {
Debug.e("showProgress Exception", e.getMessage());
}
}
});
}
public class ResponseHandler extends AsyncResponseHandler {
PostHolder holder ;
int position;
Activity activity;
public ResponseHandler(Activity context,final View holder,
final int position) {
super(context);
this.position = position;
this.activity=context;
this.holder= (PostHolder) holder.getTag();
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onFinish() {
super.onFinish();
try {
} catch (Exception e) {
Debug.e("ResponseHandler onFinish Exception", e.getMessage());
}
}
@Override
public void onSuccess(String response) {
try {
Debug.e("ResponseHandler", "onSuccess" + response);
if (response != null && response.length() > 0) {
final AddLike styleListRider = new Gson().fromJson(
response, new TypeToken<AddLike>() {
}.getType());
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (styleListRider.statusCode == 1) {
if(styleListRider.message.equals("Like
Successfully")){
movieResults.get(position).likeStatus="Like";
countvalue =
movieResults.get(position).likeCount++;
Log.e("position null",position+"");
holder.imgLike.setImageResource(R.drawable.like);
if(movieResults.get(position).likeCount > 0)
{
holder.likeCount.setVisibility(View.VISIBLE);
holder.likeCount.setText(movieResults.get(position).likeCount+" Likes");
}else {
holder.likeCount.setVisibility(View.GONE);
}
}else{
movieResults.get(position).likeStatus="UnLike";
countvalue =
movieResults.get(position).likeCount--;
holder.imgLike.setImageResource(R.drawable.unlike);
if(movieResults.get(position).likeCount > 0)
{
holder.likeCount.setVisibility(View.VISIBLE);
holder.likeCount.setText(movieResults.get(position).likeCount+" Likes");
}else {
holder.likeCount.setVisibility(View.GONE);
}
}
} else if(styleListRider.statusCode == 0){
Log.e("message",styleListRider.message);
}
}
});
}
} catch (Exception e) {
Debug.e("ResponseHandler onSuccess Exception", e.getMessage());
}
}
@Override
public void onFailure(Throwable e, String content) {
Debug.e("Response ", "onFailure" + e.getMessage());
}
}
public class PostHolder extends RecyclerView.ViewHolder {
private View view;
@Bind(R.id.postedImg)
ImageView postedImg;
@Bind(R.id.postedTime)
TextView postedTime;
@Bind(R.id.userPic)
ImageView userPic;
@Bind(R.id.imgLike)
CheckBox imgLike;
@Bind(R.id.userName)
TextView userName;
@Bind(R.id.postedMsg)
TextView postedMsg;
@Bind(R.id.imgShare)
ImageView imgShare;
@Bind(R.id.dltPost)
ImageView dltPost;
@Bind(R.id.imgComment)
ImageView imgComment;
@Bind(R.id.likeCount)
TextView likeCount;
@Bind(R.id.commentCount)
TextView commentCount;
@Bind(R.id.shareCount)
TextView shareCount;
@Bind(R.id.videoLayout)
FrameLayout videoLayout;
@Bind(R.id.likeLayout)
LinearLayout likeLayout;
@Bind(R.id.viewLine)
View viewLine;
@Bind(R.id.viewLineAd)
View viewLineAd;
@Bind(R.id.adView)
NativeExpressAdView adView;
@Bind(R.id.progress)
ProgressBar progress;
@Bind(R.id.commentLayout)
LinearLayout commentLayout;
@Bind(R.id.shareLayout)
LinearLayout shareLayout;
public PostHolder(View itemView) {
super(itemView);
this.view = itemView;
ButterKnife.bind(this, view);
}
}
}
需要帮助并提前感谢
答案 0 :(得分:0)
OnBindViewHolder中的任何代码都应该尽可能快,否则滚动会不顺畅,所以尝试在另一个线程上做长时间的工作。例如,您使用AdBuilder加载广告,这将耗费大量时间并会产生滚动问题。
答案 1 :(得分:-1)
试试这个。
recyclerView.setNestedScrollingEnabled(false);
希望这会有所帮助。