ListView项onClickListener和垃圾收集器 [英] ListView item onClickListener and garbage collector

查看:153
本文介绍了ListView项onClickListener和垃圾收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ListView和一个ArrayAdapter。在方法getView我创建的每个列表元素上的按钮。
这里是我的code的方法的onClick

I have a ListView and an ArrayAdapter. In method getView I create button on each list element. Here is my code for the method onClick

public void onClick(View view) {
    mediaPlayer = MediaPlayer.create(context, audioResourceId);
    mediaPlayer.start();
    button.setBackgroundResource(R.drawable.ic_mic_pressed);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            mp.release();
            button.setBackgroundResource(R.drawable.ic_mic);
        }
    });
}

所以,如果我点击一个按钮,滚动到列表的底部,声音被打断。我认为这是因为中断这个列表项超出屏幕,并垃圾收集。

So if I click a button, and scroll to the bottom of the list, the sounds get interrupted. I think it is interrupted because this List Item is out of screen and is garbage collected.

我怎么可以让这种声音播放到结束,即使我的ListView滚动到下,或切换视图?

How I can make this sound play till the end, even if I scroll ListView to bottom, or switch views?

推荐答案

您要创建一个单独的线程持有你的的MediaPlayer 对象。当你点击该按钮,将消息发送给该线程告诉它你要玩什么音频资源。

You want to create a separate thread which holds your MediaPlayer object. When you click on the button, send a message to that thread telling it what audio resource you want to play.

做到这一点最简单的方法可能是使用处理器对象将管理你的线程,并创建一个消息队列与之通信。

The easiest way to do this is probably using an Handler object, which will manage your thread and create a message queue for communicating with it.

这篇关于ListView项onClickListener和垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆