Viewpager操作触发了错误参考

问题描述 投票:0回答:1

我有一个Viewpager我在哪里加载不同类别的数据。我想,只要用户停留在一个特定的类别5秒以上,询问用户是否他/她想要分享的内容,以显示一个自定义对话框弹出。对于我已经使用了自定义对话框,我隐藏/显示基于的条件。

但问题是,如果我想,如果用户在位置保持Viewpager项,打开对话框让我们说3,对话是在第4位打开了Viewpager项目。

我不知道为什么它引用了错误的Viewpager项目。我包括适配器类的引用代码。

article adapter.Java

public class ArticleAdapter extends PagerAdapter {

    public List<Articles> articlesListChild;
    private LayoutInflater inflater;
    Context context;
    View rootView;
    View customArticleShareDialog, customImageShareDialog;
    public int counter = 0;
    int contentType = 0;
    int userId;

    public ArticleAdapter(Context context, List<Articles> articlesListChild, int userId) {
        super();
        this.context = context;
        this.userId = userId;
        this.articlesListChild = articlesListChild;
    }

    @Override
    public int getCount() {
        return articlesListChild.size();
    }

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager) collection).removeView((View) view);
    }

    private Timer timer;
    private TimerTask timerTask;

    public void startTimer() {
        timer = new Timer();
        initializeTimerTask();
        timer.schedule(timerTask, 5*1000, 5*1000);
    }
    private void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                switch (contentType) {
                    case 1:
                        showShareDialog("articles");
                        break;
                    case 2:
                        showShareDialog("images");
                        break;
                    default :
                        // Do Nothing
                }
            }
        };
    }

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

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        inflater = LayoutInflater.from(container.getContext());
        View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);

        final ImageView contentIv, imageContentIv;
        final TextView sharingTextTv;
        final LinearLayout articleShareBtn, articlesLayout, imagesLayout, customArticleShareDialog, customImageShareDialog;

        contentIv = viewLayout.findViewById(R.id.content_iv);
        articleShareBtn = viewLayout.findViewById(R.id.article_share_btn);
        articlesLayout = viewLayout.findViewById(R.id.articles_layout);
        imagesLayout = viewLayout.findViewById(R.id.images_layout);
        imageContentIv = viewLayout.findViewById(R.id.image_content_iv);
        sharingTextTv = viewLayout.findViewById(R.id.sharing_text_tv);
        customArticleShareDialog = viewLayout.findViewById(R.id.articles_share_popup);
        customImageShareDialog = viewLayout.findViewById(R.id.images_share_popup);

        rootView = viewLayout.findViewById(R.id.post_main_cv);
        viewLayout.setTag(rootView);
        articleShareBtn.setTag(rootView);

        // Images
        if (articlesListChild.get(position).getArticleCatId() == 1) {
            articlesLayout.setVisibility(GONE);
            imagesLayout.setVisibility(View.VISIBLE);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder);
            Glide.with(context)
                    .setDefaultRequestOptions(requestOptions)
                    .load(articlesListChild.get(position).getArticleImage())
                    .into(imageContentIv);
            imageContentIv.setScaleType(ImageView.ScaleType.FIT_XY);
            sharingTextTv.setText("Found this image interesting? Share it with your friends.");
            counter = 0;
            startTimer();
        // Articles
        } else if (articlesListChild.get(position).getArticleCatId() == 2){
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.placeholder);
            articlesLayout.setVisibility(View.VISIBLE);
            Glide.with(context)
                    .setDefaultRequestOptions(requestOptions)
                    .load(articlesListChild.get(position).getArticleImage())
                    .into(contentIv);
            contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
            sharingTextTv.setText("Found this article interesting? Share it with your friends.");
            counter = 0;
            startTimer();
        }
        container.addView(viewLayout, 0);
        return viewLayout;

    }

    public void showShareDialog(String categoryType) {
        if (categoryType.equalsIgnoreCase("articles")) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    customArticleShareDialog.setVisibility(View.VISIBLE);
                }
            });
        } else if (categoryType.equalsIgnoreCase("images")) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    customImageShareDialog.setVisibility(View.VISIBLE);
                }
            });
        }
    }

}

article activity.Java

public class ArticleActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.articles_view_pager)
    ViewPager articlesViewPager;
    @BindView(R.id.constraint_head_layout)
    CoordinatorLayout constraintHeadLayout;
    private ArticleAdapter articleAdapter;
    private List<List<Articles>> articlesList = null;
    private List<Articles> articlesListChild = new ArrayList<>();
    private List<Articles> articlesListChildNew = new ArrayList<>();
    SessionManager session;
    Utils utils;
    final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1;
    int userIdLoggedIn;
    LsArticlesSharedPreference lsArticlesSharedPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        toolbar.setTitle("");
        toolbar.bringToFront();

        session = new SessionManager(getApplicationContext());
        if (session.isLoggedIn()) {
            HashMap<String, String> user = session.getUserDetails();
            String userId = user.get(SessionManager.KEY_ID);
            userIdLoggedIn = Integer.valueOf(userId);
        } else {
            userIdLoggedIn = 1000;
        }
        utils = new Utils(getApplicationContext());

        String storedTime = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("lastUsedDate", "");
        System.out.println("lastUsedDate : " + storedTime);

        if (utils.isNetworkAvailable()) {
            insertData();
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            toggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.colorWhite));
            drawer.addDrawerListener(toggle);
            if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            }
            articleAdapter = new ArticleAdapter(getApplicationContext(), articlesListChild, userIdLoggedIn);
            toggle.syncState();
            clickListeners();
            toolbar.setVisibility(View.GONE);
        } else {
            Intent noInternetIntent = new Intent(getApplicationContext(), NoInternetActivity.class);
            startActivity(noInternetIntent);
        }
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            finishAffinity();
            super.onBackPressed();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_refresh:
                articleAdapter.notifyDataSetChanged();
                insertData();
                Toast.makeText(this, "Refreshed", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    public void clickListeners() {

    }

    private void insertData() {
        Intent intent = new Intent(getBaseContext(), OverlayService.class);
        startService(intent);
        final SweetAlertDialog pDialog = new SweetAlertDialog(ArticleActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);
        pDialog.show();
        Api.getClient().getHomeScreenContents(userIdLoggedIn, new Callback<ArticlesResponse>() {
            @Override
            public void success(ArticlesResponse articlesResponse, Response response) {
                articlesList = articlesResponse.getHomeScreenData();
                if (!articlesList.isEmpty()) {
                    for (int i = 0; i < articlesList.size(); i++) {
                        articlesListChildNew = articlesList.get(i);
                        articlesListChild.addAll(articlesListChildNew);
                    }
                    articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
                    articlesViewPager.setAdapter(articleAdapter);
                    articleAdapter.notifyDataSetChanged();
                    pDialog.dismiss();

                } else {
                    List<Articles> savedArticles = lsArticlesSharedPreference.getFavorites(getApplicationContext());
                    if (!savedArticles.isEmpty()) {
                        articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, savedArticles, userIdLoggedIn, toolbar);
                        articlesViewPager.setAdapter(articleAdapter);
                        articleAdapter.notifyDataSetChanged();
                        pDialog.dismiss();
                    } else {
                        Api.getClient().getAllArticles(new Callback<AllArticlesResponse>() {
                            @Override
                            public void success(AllArticlesResponse allArticlesResponse, Response response) {
                                articlesListChild = allArticlesResponse.getArticles();
                                articleAdapter = new ArticleAdapter(getApplicationContext(), articlesList, articlesListChild, userIdLoggedIn, toolbar);
                                articlesViewPager.setAdapter(articleAdapter);
                                articleAdapter.notifyDataSetChanged();
                            };

                            @Override
                            public void failure(RetrofitError error) {
                                Log.e("articlesData", error.toString());
                            }
                        });
                        pDialog.dismiss();
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                pDialog.dismiss();
                Toast.makeText(ArticleActivity.this, "There was some error fetching the data.", Toast.LENGTH_SHORT).show();
            }
        });

    }

}
android android-viewpager adapter
1个回答
0
投票

问题原因:

你面对这个问题,因为在后台预加载viewpager片段。这意味着,当你看到第三个片段中,viewpager就是实例4。由于这种工作流程你的第三个屏幕计时器被取消,定时器4的屏幕开始。看看这个link明白是怎么回事。

解:

我接下来会做:

  1. 然后设置页面更改侦听器适配器。 How to do it
  2. 在这个监听器,你可以得到当前页面,并开始为这个页面计时器(并取消计时器先前可见的页面)。
  3. 当你在startTimer()方法实例化项目不需要调用instantiateItem()方法。
© www.soinside.com 2019 - 2024. All rights reserved.