android - 如何使用 RecyclerView 在 ListView 中更改播放/暂停音频图标?

标签 android android-studio listview audio android-recyclerview

所以我想在播放音频时单击关联的列表项时将播放图标更改为暂停图标,并在播放完成后再次将其替换为播放图标。
这是我的主要 Activity 代码:

公共(public)类 MainActivity 扩展 AppCompatActivity {

/** Handles playback of all the sound files */
private MediaPlayer mMediaPlayer;

/** Handles audio focus when playing a sound file */
private AudioManager mAudioManager;

/**
 * This listener gets triggered whenever the audio focus changes
 * (i.e., we gain or lose audio focus because of another app or device).
 */
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    @Override
    public void onAudioFocusChange(int focusChange) {
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
            // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
            // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
            // our app is allowed to continue playing sound but at a lower volume. We'll treat
            // both cases the same way because our app is playing short sound files.

            // Pause playback and reset player to the start of the file. That way, we can
            // play the word from the beginning when we resume playback.
            mMediaPlayer.pause();
            mMediaPlayer.seekTo(0);
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
            mMediaPlayer.start();


        } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
            // The AUDIOFOCUS_LOSS case means we've lost audio focus and
            // Stop playback and clean up resources
            releaseMediaPlayer();
        }
    }
};

/**
 * This listener gets triggered when the {@link MediaPlayer} has completed
 * playing the audio file.
 */
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        // Now that the sound file has finished playing, release the media player resources.
        releaseMediaPlayer();
        ImageView im =(ImageView) findViewById(R.id.image);
        im.setImageResource(R.drawable.play);

    }
};

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

    // Create and setup the {@link AudioManager} to request audio focus
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Create a list of words
    final ArrayList<Word> words = new ArrayList<Word>();
    words.add(new Word("one", "un", R.drawable.number_one, R.raw.number_one));
    words.add(new Word("two", "deux", R.drawable.number_two, R.raw.number_two));...........

    // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
    // adapter knows how to create list items for each item in the list.
    WordAdapter adapter = new WordAdapter(this, words);

    // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
    // There should be a {@link ListView} with the view ID called list, which is declared in the
    // word_list.xml layout file.
    ListView listView = (ListView) findViewById(R.id.list);

    // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
    // {@link ListView} will display list items for each {@link Word} in the list.
    listView.setAdapter(adapter);



    // Set a click listener to play the audio when the list item is clicked on
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // Release the media player if it currently exists because we are about to
            // play a different sound file
            releaseMediaPlayer();

            // Get the {@link Word} object at the given position the user clicked on
            Word word = words.get(position);

            // Request audio focus so in order to play the audio file. The app needs to play a
            // short audio file, so we will request audio focus with a short amount of time
            // with AUDIOFOCUS_GAIN_TRANSIENT.
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                    AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                // We have audio focus now.

                // Create and setup the {@link MediaPlayer} for the audio resource associated
                // with the current word
                mMediaPlayer = MediaPlayer.create(MainActivity.this, word.getAudioResourceId());

                // Start the audio file
                mMediaPlayer.start();

                ImageView im =(ImageView) view.findViewById(R.id.image);
                im.setImageResource(R.drawable.pause);


                // Setup a listener on the media player, so that we can stop and release the
                // media player once the sound has finished playing.
                mMediaPlayer.setOnCompletionListener(mCompletionListener);
            }
        }
    });
}

@Override
protected void onStop() {
    super.onStop();
    // When the activity is stopped, release the media player resources because we won't
    // be playing any more sounds.
    releaseMediaPlayer();
}

/**
 * Clean up the media player by releasing its resources.
 */
private void releaseMediaPlayer() {
    // If the media player is not null, then it may be currently playing a sound.
    if (mMediaPlayer != null) {
        // Regardless of the current state of the media player, release its resources
        // because we no longer need it.
        mMediaPlayer.release();

        // Set the media player back to null. For our code, we've decided that
        // setting the media player to null is an easy way to tell that the media player
        // is not configured to play an audio file at the moment.
        mMediaPlayer = null;

        // Regardless of whether or not we were granted audio focus, abandon it. This also
        // unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
        mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
    }
}

}

这是自定义适配器的代码:
public class WordAdapter extends ArrayAdapter<Word>  {


private int mColorResourceId;


public WordAdapter(Context context, ArrayList<Word> words) {
    super(context, 0, words);

}

私有(private)的相对布局 rl ;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Check if an existing view is being reused, otherwise inflate the view
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }



        Random rnd = new Random();

        int[] colors = new int[2];
        colors[0] = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        colors[1] = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));


    GradientDrawable gradientDrawable = new GradientDrawable(
            GradientDrawable.Orientation.LEFT_RIGHT,
            new int[] {colors[0],colors[1]});
    gradientDrawable.setCornerRadius(20f);

    rl = (RelativeLayout) listItemView.findViewById(R.id.rel);
    rl.setBackground(gradientDrawable);



    Word currentWord = getItem(position);


    // Find the TextView in the list_item.xml layout with the ID miwok_text_view.
    TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);
    // Get the Miwok translation from the currentWord object and set this text on
    // the Miwok TextView.
    miwokTextView.setText(currentWord.getMiwokTranslation());



    // Find the TextView in the list_item.xml layout with the ID default_text_view.
    TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);
    // Get the default translation from the currentWord object and set this text on
    // the default TextView.
    defaultTextView.setText(currentWord.getDefaultTranslation());



    // Return the whole list item layout (containing 2 TextViews) so that it can be shown in
    // the ListView.
    return listItemView;
}

}

最佳答案

似乎您需要向您的 Word 对象添加一个属性。
我建议添加一个 bool 变量“正在播放”并在单击以及完成监听器中更改其值。播放/暂停图标源应在 onBindViewHolder 中解析。
应用更改一个简单的 notifyDatasetChanged() 改变值后应该可以解决问题。
希望它至少在某种程度上有用

关于android - 如何使用 RecyclerView 在 ListView 中更改播放/暂停音频图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53614810/

相关文章:

Android 从 URL 安装 apk

android-studio - Gradle-无法获取配置容器的未知属性 'scm'

android - 如何从 AlertDialog 中由光标填充的 ListView 获取选中的值?

java - Android自定义ArrayAdapter : "unfortunately, app has stopped" while scrolling

c# - 如何将图像列表添加到 WPF ListView ?

android - 使用重力来确定世界引用系?

android - 离开 Activity 后保留变量

Android 忽略自签名证书

android - Gradle 命令在 API 23 Google API 模拟器图像 (armeabi-v7a) 上失败

android - 如何删除sqlite数据库中的重复值?