想要在点击回收者视图时实现声音或媒体播放器

时间:2016-03-19 10:02:01

标签: android android-studio android-recyclerview

在媒体播放器中,此关键字显示错误,因为我们无法在回收器视图中使用上下文,如何在单击回收器视图时播放声音。有没有办法简单地做到这一点。

public class ViewHolder extends RecyclerView.ViewHolder{
    private TextView p_name,p_quant,p_cat,p_earn;
    private ImageView p_img,plus;
    public ViewHolder(View view) {
        super(view);

        p_name = (TextView)view.findViewById(R.id.list_product);
        p_quant = (TextView)view.findViewById(R.id.list_quantity);
        p_cat = (TextView)view.findViewById(R.id.list_category);
        p_earn = (TextView)view.findViewById(R.id.earning);
        p_img = (ImageView)view.findViewById(R.id.list_productimg);
        plus = (ImageView)view.findViewById(R.id.plusoffers);

        plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                plus.setImageResource(R.drawable.check_small);
                final MediaPlayer mp;
                mp = MediaPlayer.create(this ,R.raw.applause);
                mp.start();

            }
        });
    }

}

我的logCat

Error:(91, 58) error: no suitable method found for create(<anonymous   OnClickListener>,int)
method MediaPlayer.create(Context,Uri) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to  Context)
method MediaPlayer.create(Context,int) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Context)
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some messages have been simplified; recompile with -Xdiags:verbose to  get full output
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,因为我试图在onClickListener上为自定义适配器上创建的视图实现。

如上所述,此错误的解决方法是获取视图的上下文

plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v){
                MediaPlayer mp = MediaPlayer.create(v.getContext(), R.raw.applause);
                mp.start();
            }
        });