gpt4 book ai didi

android - 如何在适配器 View 、Android、ArrayAdapter、onCheckedChanged、OnCheckedChangeListener 中为复选框添加监听器

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:47:39 25 4
gpt4 key购买 nike

enter image description here

我有一个 listView,它通过 ArrayAdapter 由小的 xml subview 填充。每个小 View 内部只有两个东西,一个复选框和旁边的一个字符串标签。

我想设置一个 onCheckedChanged 监听器来捕获用户选中或取消选中复选框的事件。

例如此处显示的监听器:

 listView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

Toast.makeText(this, "box has been checked", Toast.LENGTH_SHORT).show();

}

监听器代码放在哪里?我该如何设置?

ArrayAdapter 的代码:

  public class MobileArrayAdapter extends ArrayAdapter<CheckBoxInfo>{
CheckBoxInfo[] objects;
Context context;
int textViewResourceId;

public MobileArrayAdapter(Context context, int textViewResourceId,
CheckBoxInfo[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.textViewResourceId = textViewResourceId;
this.objects = objects;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row_layout_view = convertView;


if ((row_layout_view == null)){


LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row_layout_view = inflater.inflate(R.layout.row_layout, null);
}

//CheckBoxInfo item = objects.get(position); // for arrayList
CheckBoxInfo item = objects[position];

if(item != null){

TextView textView = (TextView) row_layout_view.findViewById(R.id.textView1);
CheckBox checkBox = (CheckBox) row_layout_view.findViewById(R.id.checkBox1);

if(item !=null){
textView.setText(item.checkBoxName);
checkBox.setChecked(item.checkBoxState);
}
}
return row_layout_view;
}


}

最佳答案

不要使用您的示例 listView.setOnCheckedChangeListeneronCheckedChanged 代码。

首先,对于CheckBox,您应该使用setOnClickListener() 而不是setOnCheckedChangeListener()。您可以在 onClick() 函数中获取选中状态。

其次,将您的 setOnClickListener() 放在列表适配器的 getView() 函数中。

示例:

checkBox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
final boolean isChecked = checkBox.isChecked();
// Do something here.
}
});

关于android - 如何在适配器 View 、Android、ArrayAdapter、onCheckedChanged、OnCheckedChangeListener 中为复选框添加监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15941635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com