ViewPager的第一页未呈现

时间:2016-07-04 07:21:42

标签: android android-viewpager

我使用ViewPager可以在视图之间滑动。我面临的问题是,第一页没有正确呈现(只有布局文件中的静态成员得到渲染),但第二页和其他页面正确呈现。此外,当我转到第三页或更晚页面然后再刷回第一页时,它会完美呈现。

我知道ViewPager加载第一页以及开头的第二页,并为每个下一页加载相同的页面。这是我的第一页没有正确呈现的原因吗?我正在每个页面上进行网络呼叫,并且返回的数据正在页面上显示。

以下是我Adapter的代码:

public class SlidingImageDetailAdapter extends PagerAdapter implements GoogleApiClient.OnConnectionFailedListener {

    Context context;

    List<ImageDetailData> list;

    List<LatestComment> latestComments;

    LayoutInflater layoutInflater;

    GaApplication application;

    protected GoogleApiClient mGoogleApiClient;

    TinyDB tinyDB;

    MixpanelAPI mixpanel;

    RestAdapter restAdapter;

    public final String TAG = getClass().getSimpleName();

    private static int radius = Utils.dpToPx(40);

    private String googlePlaceId = null;

    private String finalPlace = null;

    private String commentId = null;

    private String imageId = null;

    private String imageUrl = null;

    private boolean updateNeeded;

    private PlaceAutocompleteAdapter mAdapter;

    ImageGalleryAdapter imageGalleryAdapter;

    ImageCommentAdapter imageCommentAdapter;

    ViewHolder holder = null;

    private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
            new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));

    public SlidingImageDetailAdapter(Context context, List<ImageDetailData> list) {
        this.context = context;
        this.list = list;
        layoutInflater = LayoutInflater.from(context);
        application = (GaApplication) ((AppCompatActivity) context).getApplication();
        String API = application.getAPI();
        tinyDB = new TinyDB(context);
        mixpanel = MixpanelAPI.getInstance(context, application.getMixpanelId());
        final String token = tinyDB.getString(AppConstants.GA_ACCESS_TOKEN);
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Accept", "application/json");
                request.addHeader("Authorization", "Token " + token);
            }
        };
        restAdapter = new RestAdapter.Builder()
                .setClient(new OkClient(okHttpClient))
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(API)
                .setRequestInterceptor(requestInterceptor)
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .enableAutoManage((ImageDetailSliderActivity)context, 0 /* clientId */, this)
                .addApi(Places.GEO_DATA_API)
                .build();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        LogUtil.i(TAG, "instantiateItem called");
        View view = layoutInflater.inflate(R.layout.viewpager_image_detail, container, false);
        holder = new ViewHolder(view);
        final ImageDetailData item = list.get(position);

        imageId = item.getPhotoId();
        holder.bar.setVisibility(View.INVISIBLE);
        holder.deletePhoto.setVisibility(View.INVISIBLE);
        holder.locationIcon.setVisibility(View.GONE);
        holder.galleryList.setFocusable(false);
        holder.commentList.setFocusable(false);
        googlePlaceId = null;
        finalPlace = null;
        updateNeeded = false;
        commentId = null;
        imageUrl = null;

        final ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Loading...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        if (!TextUtils.isEmpty(item.getPhotoUrl())) {
            imageUrl = item.getPhotoUrl();
            Uri uri = Uri.parse(item.getPhotoUrl());
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                    .setProgressiveRenderingEnabled(true)
                    .build();
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(request)
                    .setOldController(holder.image.getController())
                    .build();
            holder.image.setController(controller);
        }

        Picasso.with(context)
                .load(tinyDB.getString(AppConstants.USER_DP))
                .resize(radius, radius)
                .centerCrop()
                .transform(new CircleTransform())
                .into(holder.userDp);

        TextWatcher textWatcher = new TextWatcher() {

            public void afterTextChanged(Editable s) {
                Picasso.with(context)
                        .load(R.drawable.cta_button_post)
                        .into(holder.postButton);
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (TextUtils.isEmpty(holder.writeComment.getText().toString().trim())) {
                    Picasso.with(context)
                            .load(R.drawable.cta_button_post_in_active)
                            .into(holder.postButton);
                } else {
                    Picasso.with(context)
                            .load(R.drawable.cta_button_post)
                            .into(holder.postButton);
                }
            }
        };
        holder.writeComment.addTextChangedListener(textWatcher);

        holder.comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scrollToComment();
            }
        });

        holder.seeAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AllGalleriesActivity.class);
                intent.putExtra(KEY_SEND_ALL_GALLERY_PHOTO_ID, item.getPhotoId());
                context.startActivity(intent);
            }
        });

        //show and hide fab based on whether autocomplete textview has focus or not
        holder.autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ((ImageDetailSliderActivity)context).hideFab();
                } else {
                    ((ImageDetailSliderActivity)context).showFab();
                }
            }
        });

        LogUtil.i(TAG, "Id of image = " + item.getPhotoId());
        PhotoAPI photoAPI = restAdapter.create(PhotoAPI.class);
        photoAPI.getFeed(item.getPhotoId(), new Callback<ImageItem>() {
            @Override
            public void success(final ImageItem photoDetails, Response response) {
                LogUtil.i(TAG, "photo api successful");
                DialogUtils.safelyDismissDialog(progressDialog);

                holder.locationIcon.setVisibility(View.VISIBLE);

                if (TextUtils.isEmpty(item.getPhotoUrl())) {
                    imageUrl = photoDetails.getPhotoUrl();
                    item.setPhotoUrl(photoDetails.getPhotoUrl());
                    Uri uri = Uri.parse(photoDetails.getPhotoUrl());
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setProgressiveRenderingEnabled(true)
                            .build();
                    DraweeController controller = Fresco.newDraweeControllerBuilder()
                            .setImageRequest(request)
                            .setOldController(holder.image.getController())
                            .build();
                    holder.image.setController(controller);
                }

                if (photoDetails.isOwner()) {
                    holder.buttonBookmark.setVisibility(View.GONE);
                    holder.bar.setVisibility(View.VISIBLE);
                    holder.deletePhoto.setVisibility(View.VISIBLE);
                    holder.separator.setVisibility(View.VISIBLE);

                    if (TextUtils.isEmpty(photoDetails.getCaption())) {
                        holder.addCaption.setVisibility(View.VISIBLE);
                    } else {
                        holder.updateCaption1.setVisibility(View.VISIBLE);
                    }

                    if (TextUtils.isEmpty(photoDetails.getLocation())) {
                        holder.loc.setVisibility(View.GONE);
                        showAutoComplete();
                    } else {
                        holder.loc.setVisibility(View.VISIBLE);
                        holder.location.setText(photoDetails.getLocation());
                        showEditOrRemove();
                    }

                    if (photoDetails.getCampaignInfo() != null) {
                        showCleartripCampaign(photoDetails.getCampaignInfo());
                    } else {
                        showAddToExisting();
                    }
                } else {
                    if (TextUtils.isEmpty(photoDetails.getLocation())) {
                        holder.loc.setVisibility(View.GONE);
                    } else {
                        holder.loc.setVisibility(View.VISIBLE);
                        holder.location.setText(photoDetails.getLocation());
                    }
                }

                if (!TextUtils.isEmpty(photoDetails.getCaption())) {
                    holder.caption.setText(photoDetails.getCaption());
                } else {
                    holder.caption.setVisibility(View.GONE);
                }

                holder.time.setText(photoDetails.getTime());

                holder.username.setText(photoDetails.getUserName());

                holder.userFives.setText(String.format("%s Karma", Integer.toString(photoDetails.getUserKarma())));

                holder.numComments.setText(Integer.toString(photoDetails.getNumComments()));
                holder.numComments.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, CommentsActivity.class);
                        intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
                        context.startActivity(intent);
                    }
                });
                holder.commentIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, CommentsActivity.class);
                        intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
                        context.startActivity(intent);
                    }
                });

                holder.updateCaption1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        updateCaption();
                    }
                });

                holder.addCaption.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateCaption();
                    }
                });

                Picasso.with(context)
                        .load(photoDetails.getProfilePic())
                        .placeholder(R.drawable.feed_shape_profile_pic)
                        .resize(radius, radius)
                        .centerCrop()
                        .transform(new CircleTransform())
                        .into(holder.profilePic);

                holder.profilePic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, UserProfileActivity.class);
                        intent.putExtra(KEY_SEND_USER_ID, Integer.toString(photoDetails.getOwnerPk()));
                        context.startActivity(intent);
                    }
                });

                imageGalleryAdapter = new ImageGalleryAdapter(context, photoDetails.getGalleries(), item.getPhotoId());
                holder.galleryList.setAdapter(imageGalleryAdapter);
                setListViewHeightBasedOnChildren(holder.galleryList);

                latestComments = photoDetails.getLatestComments();
                imageCommentAdapter = new ImageCommentAdapter(context, latestComments);
                holder.commentList.setAdapter(imageCommentAdapter);
                setListViewHeightBasedOnChildren(holder.commentList);

                if (photoDetails.isBookmarked()) {
                    Picasso.with(context)
                            .load(R.drawable.cta_button_bookmark_secondary_state)
                            .into(holder.buttonBookmark);
                } else {
                    Picasso.with(context)
                            .load(R.drawable.cta_button_bookmark_default_state)
                            .into(holder.buttonBookmark);
                }
                holder.buttonBookmark.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!photoDetails.isBookmarked()) {
                            Picasso.with(context)
                                    .load(R.drawable.cta_button_bookmark_secondary_state)
                                    .into(holder.buttonBookmark);
                            photoDetails.setIsBookmarked(true);
                            BookmarkUserAPI api = restAdapter.create(BookmarkUserAPI.class);
                            api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
                                @Override
                                public void success(ActionResponse actionResponse, Response response) {
                                    LogUtil.i(TAG, "bookmark successful");
                                }

                                @Override
                                public void failure(RetrofitError error) {
                                    LogUtil.i(TAG, "bookmark failed");
                                }
                            });
                        } else {
                            Picasso.with(context)
                                    .load(R.drawable.cta_button_bookmark_default_state)
                                    .into(holder.buttonBookmark);
                            photoDetails.setIsBookmarked(false);
                            UnBookmarkUserAPI api = restAdapter.create(UnBookmarkUserAPI.class);
                            api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
                                @Override
                                public void success(ActionResponse actionResponse, Response response) {
                                    LogUtil.i(TAG, "unbookmark successful");
                                }

                                @Override
                                public void failure(RetrofitError error) {
                                    LogUtil.i(TAG, "unbookmark failed");
                                }
                            });
                        }
                    }
                });

                holder.deletePhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        updateNeeded = true;
                        FeedFragment.updateDelete(updateNeeded);
                        GalleryActivity.updateDelete(updateNeeded);
                        updateNeeded = !updateNeeded;

                        final Dialog dialog = new Dialog(context);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setContentView(R.layout.dialog_delete);
                        dialog.show();
                        TextView cancel = (TextView) dialog.findViewById(R.id.textView174);
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                DialogUtils.safelyDismissDialog(dialog);
                            }
                        });
                        TextView deleteButton = (TextView) dialog.findViewById(R.id.textView175);
                        deleteButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                DeletePhotoAPI deletePhotoAPI = restAdapter.create(DeletePhotoAPI.class);
                                deletePhotoAPI.delete(item.getPhotoId(), new Callback<ActionResponse>() {
                                    @Override
                                    public void success(ActionResponse actionResponse, Response response) {
                                        LogUtil.i(TAG, "image deleted successfully");
                                        Toast.makeText(context.getApplicationContext(), "Image deleted successfully", Toast.LENGTH_SHORT).show();
                                        ((ImageDetailSliderActivity) context).finish();
                                    }

                                    @Override
                                    public void failure(RetrofitError error) {
                                        LogUtil.i(TAG, "image could not be deleted");
                                    }
                                });
                            }
                        });
                    }
                });

                commentId = Integer.toString(photoDetails.getPk());

                holder.postButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        postComment();
                    }
                });

                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, AlternateFullImageActivity.class);
                        intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
                        intent.putExtra(KEY_SEND_PHOTO_URL, item.getPhotoUrl());
                        intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        context.startActivity(intent);
                        ((ImageDetailSliderActivity)context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    }
                });
            }

            @Override
            public void failure(RetrofitError error) {
                LogUtil.i(TAG, "photo api failed");
            }
        });

        container.addView(view);
        return view;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        LogUtil.i(TAG, "onConnectionFailed called");
    }

    public static class ViewHolder {
        @Bind(R.id.imageView102)
        SimpleDraweeView image;

        @Bind(R.id.textView38)
        TextView caption;

        @Bind(R.id.textView39)
        TextView time;

        @Bind(R.id.textView45)
        TextView username;

        @Bind(R.id.textView46)
        TextView userFives;

        @Bind(R.id.imageView107)
        ImageView profilePic;

        @Bind(R.id.listView2)
        ListView galleryList;

        @Bind(R.id.textView57)
        TextView seeAll;

        @Bind(R.id.listView6)
        ListView commentList;

        @Bind(R.id.editText6)
        EditText writeComment;

        @Bind(R.id.imageView108)
        ImageView buttonBookmark;

        @Bind(R.id.imageView233)
        ImageView editButton;

        @Bind(R.id.textView151)
        TextView numComments;

        @Bind(R.id.textView82)
        TextView bar;

        @Bind(R.id.textView83)
        TextView deletePhoto;

        @Bind(R.id.textView79)
        TextView comment;

        @Bind(R.id.imageView116)
        ImageView userDp;

        @Bind(R.id.rel)
        RelativeLayout rel;

        @Bind(R.id.imageView131)
        ImageView postButton;

        @Bind(R.id.editText15)
        EditText editCaption;

        @Bind(R.id.textView184)
        TextView separator;

        @Bind(R.id.textView185)
        TextView updateCaption1;

        @Bind(R.id.textView186)
        TextView updateCaption2;

        @Bind(R.id.loc)
        LinearLayout loc;

        @Bind(R.id.textView115)
        TextView location;

        @Bind(R.id.locAuto)
        RelativeLayout locAuto;

        @Bind(R.id.autoCompleteTextView)
        AutoCompleteTextView autoCompleteTextView;

        @Bind(R.id.locEdit)
        LinearLayout locEdit;

        @Bind(R.id.editLocation)
        TextView editLocation;

        @Bind(R.id.removeLocation)
        TextView removeLocation;

        @Bind(R.id.scrollView)
        ScrollView scrollView;

        @Bind(R.id.imageView173)
        ImageView locationIcon;

        @Bind(R.id.textView5)
        TextView addCaption;

        @Bind(R.id.imageView11)
        ImageView commentIcon;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

只需将此方法添加到您的班级

即可
 @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

每次进入特定布局时都会渲染。这是pagerAdapter的覆盖方法。