ListView中利用另一方法AdapterView.setOnItemClickListener來設置列表項的點擊事件監聽器

對比之間在自定義適配器中設置列表項點擊事件監聽器的方法, 這裏說明第二種方法, 這種辦法相對更好,更省內存資源

同是Miwok項目, 舉個例子, 在NumbersActivity中可以用一種方法設置列表項的點擊事件監聽器, 之間在NumbersActivity中利用listView.setOnItemClickListener()設置;

另外注意: 在播放完後, 一旦該MediaPlayer對象再被使用,應該調用release()方法將這些資源釋放.

public class NumbersActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    //This listener gets triggered when the {@link MediaPlayer} has completed
    //playing the audio files.
    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener(){
        public void onCompletion(MediaPlayer mediaPlayer){
            //Toast.makeText(NumbersActivity.this, "I'm done" , Toast.LENGTH_SHORT).show();
            //Now that the sound file has finished playing, release the media player resources.
            releaseMediaPlayer();
        }
    };

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

        //create a list of Word
        final ArrayList<Word> words = new ArrayList<Word>();

        words.add(new Word("lutti", "one", R.drawable.number_one, R.raw.number_one));
        words.add(new Word("otiiko", "two", R.drawable.number_two,R.raw.number_two));
        words.add(new Word("tolookosu", "three", R.drawable.number_three, R.raw.number_three));
        words.add(new Word("oyyisa", "four", R.drawable.number_four, R.raw.number_four));
        words.add(new Word("massokka", "five", R.drawable.number_five, R.raw.number_five));
        words.add(new Word("temmokka", "six", R.drawable.number_six, R.raw.number_six));
        words.add(new Word("kenekaku", "seven", R.drawable.number_seven, R.raw.number_seven));
        words.add(new Word("kawinta", "eight", R.drawable.number_eight, R.raw.number_eight));
        words.add(new Word("wo'e", "nine", R.drawable.number_nine, R.raw.number_nine));
        words.add(new Word("na'aacha", "ten", R.drawable.number_ten, R.raw.number_ten));

        WordAdapter wordAdapter = new WordAdapter(this, words);
        ListView listView  = (ListView)findViewById(R.id.numbers_list);
        listView.setAdapter(wordAdapter);



        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            //AdapterView: the AdapterView where the Click happened.
            //view:  the view within the AdapterView that was clicked(this will be view provided by the adapter).
            //position: the position of the view int the adapter.
            //id: the row id of the item that was clicked.
            public void onItemClick(AdapterView<?> AdapterView, View view, int position, long id) {
                //Release the media player if it currently exists because we are about to
                //play a different sound file.
                releaseMediaPlayer();
                Word currentWord = words.get(position);
                mediaPlayer = MediaPlayer.create(view.getContext(), currentWord.getAudioResourceId());
                mediaPlayer.start();
                //Setup a listener on the media player, so that we can stop and release the
                //media player once the sounds has finished playing.
                mediaPlayer.setOnCompletionListener(completionListener);
            }
        });
    }

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

            //Set the mediaPlayer 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.
            mediaPlayer = null;
        }
    }
}

注意:ListView 和GridView 同是AdapterView的子類
刪除第一種設置列表項點擊事件監聽器的方法, 即在適配器中設置點擊事件監聽器

 public class WordAdapter extends ArrayAdapter<Word> {

    /**
     * This is our own custom constructor (it doesn't mirror a superclass constructor).
     * The context is used to inflate the layout file, and the list is the data we want
     * to populate into the lists.
     *
     * @param context        The current context. Used to inflate the layout file.
     * @param words      A List of word objects to display in a list
     */
    public WordAdapter(Activity context, ArrayList<Word> words){
        super(context, 0, words);
    }

    /**
     * Provides a view for an AdapterView (ListView, GridView, etc.)
     *
     * @param position The position in the list of data that should be displayed in the list item view.
     * @param convertView The recycled view to populate.
     * @param parent The parent ViewGroup that is used for inflation.
     * @return The View for the position in the AdapterView.
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        //return super.getView(position, convertView, parent);

        // Check if the existing view is being reuse,otherwise inflate the view
        // (if convertView is null,there is no view to reuse, In this case we will need to inflate
        // one from the list item layout from scratch)
        View listItemView = convertView;
        if(listItemView == null){
            //LayoutInflater is an abstract class,and have no static method :inflate(),so
            //we should use LayoutInflater.from(getContext()) method to obtain a LayoutInflater
            //from the given context
            //
            //The third param false, because we don't want to attach the list item view to the parent list view.
            //The'getContext()' parameter is defined in ArrayAdapter.
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        //Get the object located at this position in the list. getItem() method from the super class ArrayAdapter
        final Word currentWord =  getItem(position);

        //Find the TextView in the list_item.xml layout with the id.
        //ArrayAdapter don't have the method of 'findViewById()',
        //so must have to use the method of 'View.findViewById()' to find the TextView
        TextView defaultTextView =  (TextView)listItemView.findViewById(R.id.default_text_view);
        defaultTextView.setText(currentWord.getDefaultTranslation());

        //Find the TextView in the list_item.xml layout with the id
        TextView miwokTextView = (TextView)listItemView.findViewById(R.id.miwok_text_view);
        miwokTextView.setText(currentWord.getMiwokTranslation());

        if (currentWord.checkImageResource()) {
            //Find the ImageView in the list_item.xml layout with the id
            ImageView imageView = (ImageView)listItemView.findViewById(R.id.image_view);
            imageView.setImageResource(currentWord.getImageResourceId());
        }else{
            ImageView imageView = (ImageView)listItemView.findViewById(R.id.image_view);
            imageView.setVisibility(View.GONE);
        }

        RelativeLayout textLinearLayout = (RelativeLayout)listItemView.findViewById(R.id.text_relative_layout);
        textLinearLayout.setBackgroundResource(R.color.category_numbers);


//        textLinearLayout.setOnClickListener(new View.OnClickListener(){
//            public void onClick(final View view){
//                MediaPlayer mediaPlayer = MediaPlayer.create(getContext(), currentWord.getAudioResourceId());
//                Toast.makeText(view.getContext(), "Play", Toast.LENGTH_SHORT).show();
//                mediaPlayer.start();
//                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
//
//                    public void onCompletion(MediaPlayer mediaPlayer){
//                        //Toast.makeText(view.getContext(),"I'm done!", Toast.LENGTH_SHORT).show();
//                        mediaPlayer.release();
//                    }
//                });
//            }
//        });


        return listItemView;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章