Android:选中checkBox时执行某些操作

时间:2017-07-06 09:45:53

标签: android layout-inflater

我创建了自定义适配器和两个布局文件 第一个布局是片段视图,其中包含ListViewButton

第二个布局包含将在ListView

中表示的项目

因此

我想在Checkbox检查时使Button可见

所有这些操作都将在我的自定义适配器类

中完成

这是myCustom适配器

更新

public class LampControllerAdapter extends BaseAdapter {
Context mContext;
List<LampModel> mLampModels;
HashMap<Long,LampModel> selection;
Button sC;

  public LampControllerAdapter(Context context, ArrayList<LampModel> lampList) {

    mContext = context;
    mLampModels = lampList;
    selection = new HashMap<Long,LampModel>();
    LayoutInflater in = (LayoutInflater) LayoutInflater.from(context);

    View v = in.inflate(R.layout.fragment_home,null);
   sC = (Button)v.findViewById(R.id.selection_control);



}

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

@Override
public Object getItem(int i) {
    return mLampModels.get(i);
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(final int i, View view, ViewGroup parent) {

    ViewHolder holder;
    final LampModel model = (LampModel) getItem(i);
    if (view == null) {
        // Inflating The Layout
        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        view = inflater.inflate(R.layout.lamp_controller_item, parent, false);
        holder = new ViewHolder();

        holder.name = (TextView) view.findViewById(R.id.lamp_item_name);
        holder.description = (TextView) view.findViewById(R.id.lamp_item_description);
        holder.select = (CheckBox) view.findViewById(R.id.lamp_item_select);
        view.setTag(holder);

    } else {
        holder = (ViewHolder) view.getTag();
    }


    holder.name.setText(model.getName());
    holder.description.setText(model.getDescription());
    holder.select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            if(b){
                selection.put(model.getId(),model);
            }else {
                selection.remove(model.getId());
            }

            if(selection.size() > 0){
                Toast.makeText(mContext, "Not Empty", Toast.LENGTH_SHORT).show();
                sC.setVisibility(View.GONE);
            }else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }

        }
    });


    return view;
}


class ViewHolder {
    TextView name, description;
    CheckBox select;
    Switch aSwitch;
}

}

1 个答案:

答案 0 :(得分:2)

试试这个

CheckBox chkBox = ( CheckBox ) findViewById( R.id.chkBox );
chkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform your action here
        }

    }
});