Android setOnCheckedChangeListener运行两次

时间:2016-07-06 09:37:21

标签: android listview checkbox

这是我的代码。什么可以成为原因?

holder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                addFavorite(famous);
            } else {
                deleteFavorite(famous);
            }
        }
    });

isChecked=true时,首先运行addFavorite(),然后运行deleteFavorite()

isChecked=false时,首先运行deleteFavorite(),然后运行addFavorite()

不知道为什么......

编辑:当我向下/向上滚动ListView时,它也会调用这些方法......很奇怪......

    private void deleteFavorite(final FamousTop40Ranking famous) {
        DeleteFavoriteData data = new DeleteFavoriteData(famous.getId());
        FavoriteDeleteApi.Factory.getInstance().deleteFavorite(data.getData())
                .enqueue(new Callback<StatusInfoModel>() {
                    @Override
                    public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
                        showToast(mActivity, "Famous deleted from your Favorites list.");
                        famous.setFollowersCountry(famous.getFollowersCountry() - 1);
                        famous.setFollowersWorld(famous.getFollowersWorld() - 1);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Call<StatusInfoModel> call, Throwable t) {
                        Log.d("deleteFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
                    }
                });
    }




private void addFavorite(final FamousTop40Ranking famous) {
        FavoriteCountApi.Factory.getInstance().countFavorites()
                .enqueue(new Callback<CountFavoriteModel>() {
                    @Override
                    public void onResponse(Call<CountFavoriteModel> call, Response<CountFavoriteModel> response) {
                        if (response.isSuccessful()) {
                            if (response.body().getCount() < 20) {
                                FavoriteAddApi.Factory.getInstance().addFavorite(String.valueOf(famous.getId()))
                                        .enqueue(new Callback<StatusInfoModel>() {
                                            @Override
                                            public void onResponse(Call<StatusInfoModel> call, Response<StatusInfoModel> response) {
                                                showToast(mActivity, "Famous added from your Favorites list.");
                                                famous.setFollowersCountry(famous.getFollowersCountry() + 1);
                                                famous.setFollowersWorld(famous.getFollowersWorld() + 1);
                                                notifyDataSetChanged();
                                            }

                                            @Override
                                            public void onFailure(Call<StatusInfoModel> call, Throwable t) {
                                                Log.d("addFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
                                            }
                                        });
                            } else {
                                showToast(mActivity, mActivity.getString(R.string.reached_max_favorites));
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CountFavoriteModel> call, Throwable t) {
                        Log.d("countFavorite", mActivity.getString(R.string.something_went_wrong) + t.getMessage());
                    }
                });
    }

getView()方法:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;

    if(convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_view_ranking_famous_single_item, parent, false);
    }

    final FamousTop40Ranking famous = famousModelList.get(position);

    holder = new ViewHolder(convertView);

    holder.name.setText(famous.getName());
    if (mTab == 0) { // RankingFamousMainFragment.TAB_FAMOUS
        holder.followers.setText(String.valueOf(famous.getFollowersWorld()));
    } else {
        holder.followers.setText(String.valueOf(famous.getFollowersCountry()));
    }

    if (famous.getIsFavorite().get(0).getFavorite().equals("1")) {
        holder.favorite.setChecked(true);
    } else {
        holder.favorite.setChecked(false);
    }

    Glide
            .with(mActivity)
            .load(famous.getPhoto())
            .fallback(R.drawable.bg_gradient)
            .error(R.drawable.bg_gradient)
            .centerCrop()
            .crossFade()
            .into(holder.photo);

    holder.favorite.setOnCheckedChangeListener(null);
    holder.favorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                addFavorite(famous);
            } else {
                deleteFavorite(famous);
            }
        }
    });

    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showToast(mActivity, mActivity.getString(R.string.famous_clicked, position));
        }
    });

    return convertView;
}

2 个答案:

答案 0 :(得分:3)

在getView中。在if / else。

之前移动setonCHecked(null)

这是hapening的原因是getView可能会被调用很多次,在这种情况下我认为它被调用,因为当你改变状态(检查/取消选中)时它会重新绘制按钮。在你的getView中,你调用setChecked来触发监听器。在调用holder.favorite.setChecked(true / false)之前将侦听器设置为null不会双触它。

关于上/下问题 - 当视图是屏幕被删除时,它是相同的。当它再次出现时,它会调用getView,因为holder.favorite.setChecked(true)激活了onCheckChangedLIstener

举个例子:

holder.favorite.setOnCheckedChangeListener(null);
holder.favorite.setChecked(true);
holder.favourite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // handle your logic
        }
    });

答案 1 :(得分:0)

我可能会迟到!..但这就是我在单选按钮上修复双触发器的方法,在我的例子中,我有一个 RadioGroup,它有助于一组单选按钮的行为。

当您单击特定的单选按钮时,您希望在“setOnCheckedChangeListener”中触发 lambda 表达式,这是正常的。

但是当您“重置”组并且不需要选择单选按钮时,您通常调用:

radioGroup.clearCheck()

radioGroup.check(-1)

但是当您这样做时,侦听器会收到 2 个调用,第一个是用于“未选中”的单选按钮, 带有单选按钮 id 的第二个调用等于 -1。

那么人工智能做了什么,对我来说是:

radioGroup.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { group, checkedId ->
    //If not -1, means that is a radio button that was been clicked (don't know yet is checked or not)
    if (checkedId > 0) {
        //Get radio button element
        val radio: RadioButton = group.findViewById(checkedId)

        // Preguntar por si esta checked == true ?
        if (radio.isChecked) {
            when (checkedId) {
                R.id.rb_1 -> {
                    viewModel.onSetPv(1)
                }
                R.id.rb_2 -> {
                    viewModel.onSetPv(2)
                }
                else -> false
            }

        }
    }

})

最好的问候!