【发布时间】:2015-11-16 22:41:50
【问题描述】:
在我的 Android Studio 应用程序中,我有一个 SD 卡中的歌曲列表,我使用自定义适配器和光标将其调整为一个列表
在列表视图中,每个列表项旁边都有一个“播放”按钮
当按钮被点击时,它会启动一个包含对应歌曲ID的intent
不幸的是,它一直传递一个不正确的 ID,当我检查位置时,它几乎总是“6”,即使我点击了不在位置 6 的不同列表项
这是点击 iamge 按钮的代码
public class Adapter extends SimpleCursorAdapter {
public Context context;
public Cursor cursor;
public int layout;
public String[] selection;
public int[] resources;
public View convertView;
ImageButton playButton;
TextView songName;
TextView artist;
ImageView albumArt;
public Adapter(Context context, int layout, Cursor cursor, String[] selection, int[] resources, int flags) {
super(context, layout, cursor, selection, resources, flags);
this.context = context;
this.layout = layout;
this.cursor = cursor;
this.resources = resources;
this.selection = selection;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//inflates list
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layout,parent,false);
songName = (TextView) convertView.findViewById(resources[0]);
artist = (TextView) convertView.findViewById(resources[1]);
albumArt = (ImageView) convertView.findViewById(resources[2]);
return convertView;
}
@Override
public void bindView(View view, Context context, final Cursor cursor) {
super.bindView(view, context, cursor);
final Cursor thisCursor = cursor;
final Context thisContext = context;
playButton = (ImageButton) convertView.findViewById(R.id.listPlay);
//set artist and text
songName.setText(cursor.getString(cursor.getColumnIndex(selection[0])));
artist.setText(cursor.getString(cursor.getColumnIndex(selection[1])));
//artwork
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
try {
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, cursor.getLong(cursor.getColumnIndex(selection[2])));
Bitmap songCoverArt = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
albumArt.setImageBitmap(songCoverArt);
}catch (Exception e){
}
//if play button is selected
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int position = thisCursor.getPosition();
//returns wrong position and id's?
//get id of song based on that position
String stringID = cursor.getString(cursor.getColumnIndex(selection[3]));
//create bundle to send
Bundle bundle = new Bundle();
//add position to bundle
bundle.putString("ID", stringID);
Intent intent = new Intent(thisContext, Home.class);
intent.putExtras(bundle);
//flag to allow this out of activty context
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
thisContext.startActivity(intent);
}
});
}
}
请注意 cursor.getColumnIndex(selection[3]))) == MediaStore.Audio.Media._ID
如果有人可以帮助我,我将非常感激!
【问题讨论】:
-
能否请您出示完整的 CursorAdapter...!因为调试问题很重要
-
我不确定没有看到整个代码,但很可能你得到的是当前视图的索引,而不是列表中项目的位置。
-
我已经把所有的代码都放在这里了
标签: android listview android-adapter simplecursoradapter cursor-position