出于某种原因,我的Long id
存储了行的位置,而不是_id
我希望获得_id,以便我可以执行onClick
上的其他一些功能这是我的代码:
public class WorkoutsFragment extends Fragment {
WorkoutsDatabaseHelper db;
SimpleCursorAdapter adapter;
ListView listContent;
Cursor cursor;
private Context mContext;
WorkoutsAdapter workoutsAdapter;
public WorkoutsFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mContext = getActivity();
db = new WorkoutsDatabaseHelper(mContext);
View rootView = inflater.inflate(R.layout.activity_workouts, container, false);
listContent = (ListView) rootView.findViewById(R.id.list);
// Create the Adapter
workoutsAdapter = new WorkoutsAdapter(mContext, cursor);
// Set the adapter to ListView
listContent.setAdapter(workoutsAdapter);
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String idString;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Clicked item _id = ", ""+id);
}
});
return rootView;
}
private void addItemsToList(){
Cursor cursor = db.getWorkoutNames();
Log.d("history.java", "finished Cursor cursor = db.getAllLogs();");
String[] from = {"_id", "workouts_name"};
int[] to = {R.id.tv_id, R.id.tv_label};
adapter = new SimpleCursorAdapter(mContext, R.layout.single_item, cursor, from, to, 0);
listContent.setAdapter(adapter);
}
public void onResume(){
super.onResume();
workoutsAdapter = new WorkoutsAdapter(mContext, cursor);
listContent.setAdapter(workoutsAdapter);
}
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
}
}
任何人都明白我可能做错了什么,以及如何纠正这个问题?
由于
如果您想查看其他代码,请告知我们。
答案 0 :(得分:0)
我意识到我在错误的文件中实现了这个。一旦我在适配器而不是片段中实现,它就能很好地工作。
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, id, Toast.LENGTH_LONG).show();
Log.d("Clicked item _id = ", "" + id);
}
});