簡體   English   中英

如何使用RecyclerView更改ListView中的播放/暫停音頻圖標?

[英]How to Change Play/Pause audio icon within a ListView using RecyclerView?

所以我想在播放音頻時單擊關聯的列表項時將播放圖標更改為帶有暫停圖標,並在完成時再次將其替換為播放圖標。 這是我主要活動的代碼:

公共類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);

}

私有RelativeLayout 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對象添加一個屬性。 我建議添加一個布爾變量“ isPlaying”,並在單擊時以及在完成偵聽器中更改其值。 播放/暫停圖標源應在onBindViewHolder中解決。 要應用更改,只需在更改值之后執行簡單的notifyDatasetChanged()即可 希望它至少在某種程度上有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM