ViewHolder持有android.widget.Switch,Switch没有响应监听器

时间:2015-09-16 03:15:31

标签: android android-adapter android-adapterview android-switch

好吧,我有一个持有人,拿着一堆除了开关之外不会改变的元素(显然)。

我减少了代码,因为它更易于阅读,我认为这将允许我在日志中看到交换机的状态被更改(这是从适配器动态生成的)。

public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
        holder = new ViewHolder();
        holder.communicationfilter = (Switch)convertView.findViewById(R.id.communicationfilter);

    holder.communicationfilter.setChecked(!kid.isBlocked());
    holder.communicationfilter.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Log.v(LOG_TAG, "Switch State="+isChecked);
    }               
    });
    convertView.setTag(holder);
    return convertView;
  }

2 个答案:

答案 0 :(得分:0)

请将Checked changed方法修改为

if(isChecked){
Log.v(LOG_TAG, "Switch State="+isChecked);
}else{
Log.v(LOG_TAG, "Switch State="+isChecked);
}

希望它有效......

答案 1 :(得分:0)

这解决了它,希望它可以帮助那些遇到同样问题的人。

holder.communicationfilter.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
    boolean isChecked) {
        if (isChecked) {
            Toast.makeText(mContext, "The switch is ON",Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG,"switch checked for" + holder.nameTxtView);
        } else {    
            Toast.makeText(mContext,"The switch is OFF", Toast.LENGTH_SHORT).show();
            Log.i(LOG_TAG,"switch unchecked" + holder.nameTxtView);
        }

        }
        });