错误的参考触发了Viewpager操作

时间:2019-02-06 13:35:35

标签: android android-viewpager adapter

我有一个Viewpager,我正在其中加载不同类别的数据。我想在用户停留在特定类别上5秒钟或更长时间询问用户是否要共享内容时显示自定义对话框弹出窗口。为此,我使用了自定义对话框,并根据情况进行了隐藏/显示。

但是问题是,如果用户要停留在Viewpager项的位置为3时我要打开对话框,则对话框是为Viewpager项在位置4处打开的。

我不确定为什么它引用了错误的Viewpager项目。 我包括了Adapter类的代码以供参考。

ArticleAdapter.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);
                }
            });
        }
    }

}

ArticleActivity.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();
            }
        });

    }

}

1 个答案:

答案 0 :(得分:0)

问题原因:

您会遇到此问题,因为viewpager在后台预加载了片段。这意味着当您看到第三个片段时,viewpager实例化了第四个片段。由于此工作流程,您取消了第三个屏幕的计时器,并启动了第四个屏幕的计时器。查看此link,了解发生了什么情况。

解决方案:

我接下来要做:

  1. 然后为适配器设置页面更改侦听器。 How to do it

  2. 在此侦听器中,您可以获取当前页面并为此页面启动计时器(并为先前可见的页面取消计时器)。

  3. startTimer()方法中实例化项目时,无需调用instantiateItem()方法。