对比之间在自定义适配器中设置列表项点击事件监听器的方法, 这里说明第二种方法, 这种办法相对更好,更省内存资源

同是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();}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_numbers);//create a list of Wordfinal 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@Overridepublic 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 ArrayAdapterfinal 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 TextViewTextView defaultTextView =  (TextView)listItemView.findViewById(R.id.default_text_view);defaultTextView.setText(currentWord.getDefaultTranslation());//Find the TextView in the list_item.xml layout with the idTextView 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 idImageView 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;}
}

ListView中利用另一方法AdapterView.setOnItemClickListener来设置列表项的点击事件监听器相关推荐

  1. js中动态添加/插入HTML代码块,并通过JQuery动态绑定点击事件

    文章目录 前言 一.场景需求还原 二.代码示例 1.引入JQuery库 2.代码示例 一:HTML中div标签部分 二:HTML中script标签部分 三:JS文件部分 总结 前言 本篇文章中讲的是在 ...

  2. android 控件监听方法,Android界面控件(2)—注册点击事件监听器

    Button和ImageButton 1.添加控件 1.打开Android项目下,res文件夹中的 layout 的 activity_main.xml 文件 2.可视化界面拖拽添加或修改 xml 文 ...

  3. python button使用方法_python 批量添加的button 使用同一点击事件的方法

    python 批量添加的button 使用同一点击事件根据传递的参数进行区分. def clear_text(): print '我只是个清空而已' def clear_text(index): pr ...

  4. idea中添加类、方法注释,快捷键设置

    方法一: Settings ->Keymap ->Other ->Fix doc comment ->右键 ->选择 Add Keyboard Shortcut, 然后输 ...

  5. android列表集合点击事件,给ListeView列表中的每一个Item添加点击事件

    首先声明本文主要是在ArrayAdapter.SimpleAdapter中对ListView的每一项进行点击事件! 先看下运行结果 第一步:在xml布局中写一个ListView android:lay ...

  6. ListView的Item点击事件(消息传递)

    转载请保留原文出处"http://my.oschina.net/gluoyer/blog",谢谢! 您可以到博客的"友情链接"中,"程序猿媛(最新下载 ...

  7. Excel中利用宏批量生成md5加密

    ** Excel中利用宏批量生成md5加密 一.下载宏文件 点击下载md5宏.xla 二.找到excle并加载宏 1.依次打开[文件]-[选项]-[自定义功能区] 选中[开发工具] 2.这样在Exce ...

  8. 在.net中序列化读写xml方法的总结(转载)

    阅读目录 开始 最简单的使用XML的方法 类型定义与XML结构的映射 使用 XmlElement 使用 XmlAttribute 使用 InnerText 重命名节点名称 列表和数组的序列化 列表和数 ...

  9. iOS中利用UISearchBar实现搜索

    先把源码贴出来 https://github.com/losedMemory/ZSSearchBar   这是我在github上写的一个Demo,大家可以看看 在大多数app中都会用到搜索功能,那么搜 ...

最新文章

  1. 区块链为什么这么热?有这么大热度的原因是什么
  2. R语言ggplot2可视化:ggplot2中使用element_text函数设置轴标签文本粗体字体(bold text,使x轴和Y轴的标签文本都使用粗体字体)、注意是轴标签而非轴标题
  3. .NET中使用NLog记录日志
  4. 数据库本地服务器为空,本地搭建的服务器访问不到数据库数据
  5. dbcp连接mysql,8小时会自动断开连接
  6. document write的用法
  7. 中国抗生素骨水泥行业市场供需与战略研究报告
  8. linux pandas教程_Python Anaconda教程–了解最受欢迎的数据科学平台
  9. 异地多活,企业上云的必然趋势!
  10. C#获取文件/文件夹默认图标
  11. js 实现纯前端将数据导出excel两种方式,亲测有效
  12. python光标图片获取
  13. 职业学校计算机课评课,中职计算机评课稿
  14. w ndows无法识别usb,surface pro3 windows无法识别USB设备
  15. 除了高额房贷,美国购房者仍面临其他“财政危机”
  16. java 执行Linux命令并打印执行结果
  17. 数据预处理-离群值检测与处理
  18. 数据分析——用户粘性指标 DAU/MAU
  19. 会声会影2022旗舰终极版详细功能介绍
  20. 八种酒吧里最时尚的喝酒法

热门文章

  1. NXP iMX8 存储性能测试
  2. 机器学习(五)模型评估与优化
  3. JAVA将HTML转化图片最靠谱的方法
  4. Python学习笔记——鸭子类型(duck typing)
  5. Rockland TMB ELISA过氧化物酶底物
  6. 基础研究和前沿技术领域校企融合协同创新的国际经验及启示
  7. 安全防御之反病毒网关
  8. Henrik Kniberg:乐高的基于社交的大规模敏捷计划会
  9. Ruby on Rails 教程之快速入门
  10. python趣味编程从入门到人工智能答案-趣味编程挑战:从Python入门到AI应用