我有一个列表视图,其中填充了复选框列表。我想添加一个按钮,当我按下它时,它会为列表视图中选择的每个项目执行...是什么样的最佳方法来查找复选框检查了吗?我知道我可以使用setOnCheckedChangeListener
但我如何为列表中的每个复选框调用?如果我创建一个数组字符串,每次我的复选框选中它将其文本添加到数组列表然后我可以执行循环对于每个选定的项目?
这是我的代码傀儡列表视图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_list);
File path=new File(ClubCP.SDcardPath);
List<String> file_lists = main.directoryPath(path);
ListView Database_list=(ListView)findViewById(R.id.database_list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.database_list_item,R.id.chk_database_list_item,file_lists);
ArrayAdapter<String> adapter1 = new InteractiveArrayAdapter(this,file_lists);
Database_list.setAdapter(adapter1);
}
我搜索过,我想我必须使用ArrayAdapter ..我正在写它的类..这是我的班级 包co.tosca.persianpoem;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class InteractiveArrayAdapter extends ArrayAdapter<String> {
private final List<String> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<String> list) {
super(context, R.layout.database_list_item, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected CheckBox checkbox;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.database_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.chk_database_list_item);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
///do sth
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
return view;
}
}
感谢您的帮助
答案 0 :(得分:1)
您需要子类化ArrayAdapter并覆盖getView
方法,以便您可以基于每个视图调用setOnClickListener
。请参阅ArrayAdapter文档:here
public View getView (int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
LayoutInflater li = LayoutInflater.from(getContext());
itemView = li.inflate(R.layout.database_list_item);
}
CheckBox cb = (CheckBox)itemView.findViewById(R.id.checkbox); // whatever the id of checkbox is in layout
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox myCb = (CheckBox)v;
if (myCb.isChecked()) {
// add position to array representing selected items
} else {
// remove position from array
}
}
});
return itemView;
}