我必须对我现有的应用程序进行一些小改动。它有一个listview,它从数据库中获取数据并使用自定义simplecursoradapter显示它。
我需要在自定义列表视图中显示的图像上对onclick侦听器进行一些更改。
我无法获得列表视图中点击的项目的正确数据。
ListItem
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight">
<TextView
android:id="@+id/tvWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/ivSpeak"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
</RelativeLayout>
Cursor temp=mDbHelper.fetchAllNotes();
String[] from=new String[]{DbAdapter.KEY_WORD};
int[] to= new int[]{R.id.tvWord};
words = new MySimpleCursorAdapter(this.getActivity(), R.layout.word_list_item, temp, from, to);
public Cursor fetchAllNotes(){
return mDb.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_WORD}, null, null, null, null, null);
}
public class MySimpleCursorAdapter extends SimpleCursorAdapter{
Cursor temp;
public MySimpleCursorAdapter(Context context, int layout, Cursor cursor,
String[] from, int[] to) {
super(context, layout, cursor, from, to);
temp=cursor;
temp.moveToFirst();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=super.getView(position, convertView, parent);
ImageView ivSpeak=(ImageView) row.findViewById(R.id.ivSpeak);
final TextView tvWord=(TextView) row.findViewById(R.id.tvWord);
temp.moveToPosition(position);
final int pos=position;
ivSpeak.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try{
Log.d("ambit", temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_WORD))+"word"); // This is not giving the correct word in my dataset
Log.d("ambit", pos + "position"); //This is fine
}
catch (Exception e){
e.printStackTrace();
}
}
答案 0 :(得分:0)
在onClickListener上尝试moveToPosition()你的Cursor:
@Override
public void onClick(View v) {
try{
temp.moveToPosition(position);
Log.d("ambit", temp.getString(temp.getColumnIndexOrThrow(DbAdapter.KEY_WORD))+"word"); // This is not giving the correct word in my dataset
Log.d("ambit", pos + "position"); //This is fine
}
catch (Exception e){
e.printStackTrace();
}
}