我有这个使用游标适配器的代码:
public class TemplateActivity extends Activity {
Button btnSort, btnDel;
private ListViewAdapter listAdapter;
private RetailerDatabaseHelper dbHelper;
private ListView listView;
private static final String TAG = TemplateActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
btnSort = (Button) findViewById(R.id.btnSort);
btnDel = (Button) findViewById(R.id.btnDelete);
dbHelper = new RetailerDatabaseHelper(this);
listView = (ListView) findViewById(R.id.listViewData);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "clicked on item: " + position);
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
listAdapter = new ListViewAdapter(TemplateActivity.this, dbHelper.getAllData());
listView.setAdapter(listAdapter);
}
});
我的问题是,如何在点击数据时从列表视图中获取数据的值。
这是我的适配器:
public class ListViewAdapter extends CursorAdapter {
public ListViewAdapter (Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.custom_dialog_box, parent, false);
return retView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.checkBox1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view.findViewById(R.id.number);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
}
另一件事。我将如何在这里实施,当我选中一个复选框并按下按钮时,它将获得复选框的数据?谢谢大家的帮助。
答案 0 :(得分:0)
我没有使用过ListViewAdapter,但我和你的情节相同。 我使用了CustomAdapter类扩展Baseadapter并使用自定义布局。通过这种方式,您可以单独为每个视图设置OnClicklistners(复选框,按钮,总布局......)。
答案 1 :(得分:0)
在OnItemClickListener
中执行此操作的最简单方法是:
Cursor c = ((ListViewAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);
然后,您可以使用c.getLong(0);
来获取ID(假设您将id列作为第一列获取,通常就是这种情况)。
第二个问题:(获取检查项目清单):
您可以在setOnCheckedChangeListener (CompoundButton.OnCheckedChangeListener listener)
的{{1}}方法中为Checkbox
写bindView()
,然后检查项目,然后将项目添加到列表中,如果未选中则从列表中删除该项目。