草庐IT

如果单击上一项,Android PagerAdapter 不会报告正确的位置

coder 2023-11-21 原文

我有一个带负边距的 ViewPager 设置来获得这样的效果:

现在,我想要发生的是,当我单击当前 View 左侧或右侧的 View 时。它应该选择该 View 并调用 ViewPager 上的 setCurrentItem()。这适用于当前项目右侧的 View ,但不适用于当前项目左侧的 View 。当我单击该 View 时,向我报告的位置是当前 View 的位置。

如果有帮助,这里有一些代码。这是来 self 在 onClick() 上触发的 PagerAdapter.instantiateItem():

    @Override
    public Object instantiateItem(final ViewGroup container, final int position)
    {
        cardLayout.setTag(profile);
        cardLayout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                // mOnItemClickListener passed in to adapter on initialization
                mOnItemClickListener.onItemClick(null, view, position, 0);
                // other stuff happens here as well
            }
        });
    }

所有感兴趣的人的整个 PagerAdapter 类:

static class GiveTenPagerAdapter extends PagerAdapter
{
    private final int ANIMATION_DURATION;
    private ListenerOnGiveTakeClick mListenerOnGiveTakeClick;
    private List<GiveTen> mGiveTens;
    private Context mContext;
    private LayoutInflater mInflater;

    private boolean mIsCrossFadeAnimationRunning;
    private int mSquarePhotoSideLength;

    GiveTenPagerAdapter(List<GiveTen> giveTens, Context context,
                        ListenerOnGiveTakeClick listenerOnGiveTakeClick)
    {
        mGiveTens = giveTens;
        mContext = context;
        mListenerOnGiveTakeClick = listenerOnGiveTakeClick;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        ANIMATION_DURATION = mContext.getResources().getInteger(android.R.integer.config_mediumAnimTime);
    }

    List<GiveTen> getGiveTens()
    {
        return this.mGiveTens;
    }

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

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

    @Override
    public Object instantiateItem(final ViewGroup container, final int position)
    {
        Logger.d("position=" + position);

        final GiveTen giveTen = mGiveTens.get(position);
        final UserProfile profile = giveTen.getUserProfile();

        final RelativeLayout cardLayout = (RelativeLayout) mInflater.inflate(R.layout.give_ten_card, null);
        final RelativeLayout profilePicLayout = (RelativeLayout) cardLayout.findViewById(R.id.give_ten_profile_pic_layout);
        final ImageView profileImageView = (ImageView) cardLayout.findViewById(R.id.give_ten_profile_pic);
        final View viewFiller = cardLayout.findViewById(R.id.view_filler);
        final int RADIUS = Math.round(mContext.getResources().getDimension(R.dimen.give_ten_card_corner_radius));

        profileImageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
        {
            @Override
            public boolean onPreDraw()
            {
                profileImageView.getViewTreeObserver().removeOnPreDrawListener(this);

                //kv Using Math.max() to ensure that at least 1 dimension is positive
                //kv in case of some fucked up situation where the measured width and
                //kv height returns 0
                int widthProfileImageView = Math.max(profileImageView.getMeasuredWidth(), 1);
                int heightCardLayout = Math.max(profileImageView.getMeasuredHeight(), 1);

                //kv Somehow we can get into a situation where we in this PreDrawListener and there
                //kv are not give tens, which of course gives us a crash on mGiveTens.get(position)
                //kv If we find ourselves in that case, just show icon_photo_placement_lg
                if (mGiveTens.size() > 0)
                {
                    Picasso picasso = Picasso.with(Bakery.getInstance());
                    picasso.setIndicatorsEnabled(BuildConfig.DEBUG);
                    picasso.load(mGiveTens.get(position).getUserProfile().getProfilePic().getUrl())
                            .noFade()
                            .resize(widthProfileImageView, heightCardLayout)
                            .centerCrop()
                            .transform(new PicassoTransformationRounded(RADIUS, 0))
                            .into(profileImageView);
                }
                else
                {
                    profileImageView.setImageResource(R.drawable.icon_photo_placement_lg);
                }

                return true;
            }
        });

        TextView profilePicGenderCriteriaTextView = (TextView) cardLayout.findViewById(R.id.give_ten_profile_pic_textview_gender_criteria);
        TextView profilePicCityTextView = (TextView) cardLayout.findViewById(R.id.give_ten_profile_pic_textview_city);

        if (profile.getCriteriaGender().equals("m"))
        {
            profilePicGenderCriteriaTextView.setText(R.string.give_ten_text_gender_criteria_male);
        }
        else
        {
            profilePicGenderCriteriaTextView.setText(R.string.give_ten_text_gender_criteria_female);
        }

        String cityText = mContext.getResources().getString(R.string.give_ten_profile_pic_text_city_prefix)
                + " "
                + mGiveTens.get(position).getUserProfile().getCity()
                + ", "
                + mGiveTens.get(position).getUserProfile().getState();

        profilePicCityTextView.setText(cityText);

        container.addView(cardLayout);

        final RelativeLayout giveTenDetailsLayout = getDetailsLayout(cardLayout, giveTen);

        viewFiller.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Logger.d("view=" + view);

                boolean shouldCrossFade = !mListenerOnGiveTakeClick.onGiveTenClick(position - 1, true);

                if (mIsCrossFadeAnimationRunning == false && position > 0 && shouldCrossFade)
                {
                    crossfadeViews(profilePicLayout, giveTenDetailsLayout);
                    ManagerAnalytics.sendEvent(ManagerAnalytics.EVENT_VISITED_GIVE_TEN_CARD, ManagerAnalytics.ST1_PAGEVIEW);
                }
            }
        });

        View.OnClickListener onClickListener = new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Logger.d("view=" + view);

                boolean shouldCrossFade = !mListenerOnGiveTakeClick.onGiveTenClick(position, false);

                if (mIsCrossFadeAnimationRunning == false && shouldCrossFade)
                {
                    crossfadeViews(giveTenDetailsLayout, profilePicLayout);
                    ManagerAnalytics.sendEvent(ManagerAnalytics.EVENT_VISITED_GIVE_TEN_CARD, ManagerAnalytics.ST1_PAGEVIEW);
                }
            }
        };

        cardLayout.setOnClickListener(onClickListener);

        ScrollView giveTenCardDetailScrollContainer = (ScrollView) cardLayout.findViewById(R.id.give_ten_card_detail_scroll_container);

        if (giveTenCardDetailScrollContainer != null)
        {
            LinearLayout giveTenDetailsFieldLayout = (LinearLayout) giveTenCardDetailScrollContainer.findViewById(R.id.give_ten_detail_fields_layout);

            giveTenDetailsFieldLayout.setTag(profile);
            giveTenDetailsFieldLayout.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    Logger.d("view=" + view);

                    boolean shouldCrossFade = !mListenerOnGiveTakeClick.onGiveTenClick(position, false);

                    if (mIsCrossFadeAnimationRunning == false && shouldCrossFade)
                    {
                        crossfadeViews(profilePicLayout, giveTenDetailsLayout);
                        ManagerAnalytics.sendEvent(ManagerAnalytics.EVENT_VISITED_GIVE_TEN_CARD, ManagerAnalytics.ST1_PAGEVIEW);
                    }
                }
            });
        }
        return cardLayout;
    }

    private void crossfadeViews(final View view1, final View view2)
    {
        final View visibleView, invisibleView;

        if (view1.getVisibility() == View.VISIBLE)
        {
            visibleView = view1;
            invisibleView = view2;
        }
        else
        {
            visibleView = view2;
            invisibleView = view1;
        }

        mIsCrossFadeAnimationRunning = true;
        invisibleView.setAlpha(0.0f);
        invisibleView.setVisibility(View.VISIBLE);

        invisibleView.animate()
                .alpha(1.0f)
                .setDuration(ANIMATION_DURATION)
                .setListener(new AnimatorListenerAdapter()
                {
                    @Override
                    public void onAnimationEnd(Animator animation)
                    {
                        mIsCrossFadeAnimationRunning = false;
                    }
                });

        visibleView.animate()
                .alpha(0.0f)
                .setDuration(ANIMATION_DURATION)
                .setListener(new AnimatorListenerAdapter()
                {
                    @Override
                    public void onAnimationEnd(Animator animation)
                    {
                        visibleView.setVisibility(View.GONE);
                        mIsCrossFadeAnimationRunning = false;
                    }
                });

    }

    public void crossFadeViews(View view)
    {
        final RelativeLayout giveTenDetailLayout = (RelativeLayout) view.findViewById(R.id.give_ten_detail_layout);
        final RelativeLayout profilePicLayout = (RelativeLayout) view.findViewById(R.id.give_ten_profile_pic_layout);
        crossfadeViews(profilePicLayout, giveTenDetailLayout);
    }

    private RelativeLayout getDetailsLayout(View parent, GiveTen giveTen)
    {
        RelativeLayout giveTenDetailsLayout = (RelativeLayout) parent.findViewById(R.id.give_ten_detail_layout);

        UserProfile profile = giveTen.getUserProfile();

        TextView genderCriteriaTextView = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_gender_criteria_textview);

        if (profile.getCriteriaGender().equals("m"))
        {
            genderCriteriaTextView.setText(R.string.give_ten_text_gender_criteria_male);
        }
        else
        {
            genderCriteriaTextView.setText(R.string.give_ten_text_gender_criteria_female);
        }

        TextView cityTextView = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_city_textview);
        cityTextView.setText(profile.getCity() + ", " + giveTen.getUserProfile().getState());

        TextView ageTextView = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_age_textview);
        ageTextView.setText(mContext.getResources().getString(R.string.give_ten_text_age)
                + " "
                + DateUtils.getAgeFromBirthday(profile.getBirthday()));

        TextView heightTextView = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_height_textview);
        heightTextView.setText(mContext.getResources().getString(R.string.give_ten_text_height)
                + " "
                + profile.getHeightFeet()
                + "'"
                + profile.getHeightInches());

        TextView religionTextView = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_religion_textview);
        religionTextView.setText((mContext.getResources().getStringArray(R.array.religion)[Religion.getIndex(profile.getReligionApiParam())]));

        TextView educationTextView0 = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_education_1_textview);
        TextView educationTextView1 = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_education_2_textview);

        List<String> education = profile.getEducation();
        List<Degree> degree = profile.getListDegrees();

        if (education.size() > 0)
        {
            if (degree.size() > 0)
            {
                educationTextView0.setText(education.get(0) + "/" + degree.get(0).toString().toLowerCase());
            }
            else
            {
                educationTextView0.setText(education.get(0));
            }

            if (education.size() > 1)
            {
                if (degree.size() > 1)
                {
                    educationTextView1.setText(education.get(1) + "/" + degree.get(1).toString().toLowerCase());
                }
                else
                {
                    educationTextView1.setText(education.get(1));
                }

                educationTextView1.setVisibility(View.VISIBLE);
            }
        }

        TextView occupation = (TextView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_occupation_textview);
        occupation.setText(profile.getOccupation());

        final List<ImageView> giveTenDetailPics = new ArrayList<ImageView>();
        giveTenDetailPics.add((ImageView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_pic_1));
        giveTenDetailPics.add((ImageView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_pic_2));
        giveTenDetailPics.add((ImageView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_pic_3));
        giveTenDetailPics.add((ImageView) giveTenDetailsLayout.findViewById(R.id.give_ten_detail_pic_4));

        //kv Calculate length of side for photos
        float widthPhotoLayout = ViewUtils.getScreenWidth() -
                2 * mContext.getResources().getDimension(R.dimen.give_ten_layout_margin_side) -
                2 * mContext.getResources().getDimension(R.dimen.give_ten_detail_margin_side) -
                6 * mContext.getResources().getDimension(R.dimen.give_ten_photo_margin_side);

        mSquarePhotoSideLength = (int) (widthPhotoLayout / 4);

        List<Photo> detailPhotos = profile.getPhotos();
        for (int i = 0; i < detailPhotos.size(); i++)
        {
            final ImageView imageView = giveTenDetailPics.get(i);
            final Photo photo = detailPhotos.get(i);

            final String url = photo.getUrlThumbnail();
            Logger.d("about to display " + url + ", length=" + mSquarePhotoSideLength);

            Picasso.with(mContext)
                    .load(url)
                    .noFade()
                    .resize(mSquarePhotoSideLength, mSquarePhotoSideLength)
                    .placeholder(R.drawable.icon_photo_placement_s)
                    .into(imageView, new Callback()
                    {
                        @Override
                        public void onSuccess()
                        {
                            //Logger.e("success on " + url);
                        }

                        @Override
                        public void onError()
                        {
                            Logger.e("error");
                        }
                    });
        }

        return giveTenDetailsLayout;
    }

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

最佳答案

您可以拦截触摸事件并从该事件中获取坐标。

    if(event.getRawX() < margin && canGoLeft){
goLeft();
}
else if(event.getRawX() > screenWidth - margin && canGoRight) {
goRight();
}
else { 
  // We are not interested in this event, pass it down the food chain
}

关于如果单击上一项,Android PagerAdapter 不会报告正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219706/

有关如果单击上一项,Android PagerAdapter 不会报告正确的位置的更多相关文章

  1. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  2. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  3. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  4. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  7. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  8. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

  9. ruby - 我可以将我的 README.textile 以正确的格式放入我的 RDoc 中吗? - 2

    我喜欢使用Textile或Markdown为我的项目编写自述文件,但是当我生成RDoc时,自述文件被解释为RDoc并且看起来非常糟糕。有没有办法让RDoc通过RedCloth或BlueCloth而不是它自己的格式化程序运行文件?它可以配置为自动检测文件后缀的格式吗?(例如README.textile通过RedCloth运行,但README.mdown通过BlueCloth运行) 最佳答案 使用YARD直接代替RDoc将允许您包含Textile或Markdown文件,只要它们的文件后缀是合理的。我经常使用类似于以下Rake任务的东西:

  10. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

随机推荐