【问题标题】:Getting image from listview onclicklistener从listview onclicklistener获取图像
【发布时间】:2018-04-19 08:50:24
【问题描述】:

我是一个初学者,试图为一个班级制作一个简单的音乐播放器应用程序,我的 listview 和 onclicklistener 工作得很好,但我不知道如何从单击的 listview 项目中提取 imageview 可绘制图像和在我的其他活动中显示该图像以获取“正在播放”类型的内容。

为什么这不起作用?

    public void onItemClick(AdapterView<?> parent, View view, int position, 
        long id) {
        Object listItem = listView.getItemAtPosition(position);
        startActivity(new Intent(MainActivity.this, NowPlaying.class));
        long artView = listView.getItemIdAtPosition(0);
        ImageView nowPlayingArt = 
       (ImageView)findViewById(R.id.now_playing_image);
        nowPlayingArt.setImageDrawable(artView);

【问题讨论】:

  • 请贴出完整代码并正确写出问题以便于理解。
  • 在您的适配器中调用view.setTag(your_image_id)。然后在onItemClick通过view.getTag()获取your_image_id;
  • 我有几个不同的图像用于列表视图中的不同视图,所以我需要能够从列表中单击的特定视图中获取图像

标签: android listview imageview onclicklistener


【解决方案1】:

您可以获取 ImageView 的位图,将其流式传输到 byteArray 并将其作为 Intent 的额外内容:

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
    ImageView image = view.findViewById(R.id.now_playing_image);

    Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();

    Intent intent = new Intent(MainActivity.this, NowPlaying.class);
    intent.putExtra("picture", byteArray);
    startActivity(intent);
}

然后在 NowPlaying 中,您必须从 Intent 中取回 byteArray,将其解码为位图并将位图设置为您的 ImageView:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_now_playing);

    ImageView imageView = (ImageView) findViewById(R.id.imageView);

    byte[] byteArray = getIntent().getByteArrayExtra("picture");
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    imageView.setImageBitmap(bmp);
}

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多