2017-01-02 55 views
0

我搜索該isssue的解決方案,找不到它: - 該應用程序在RecyclerView中顯示圖片 - 現在聲音播放,但只有一個爲所有項目,當你退出輸入它跳過的活動接下來的聲音 - 我要玩不同的聲音爲用戶Android Recyclerview聲音與圖片

點擊每張照片有我的適配器代碼

public class MyAdapter extends RecyclerView.Adapter { 

private static MediaPlayer mySound; 

private ArrayList<Article> mArticles = new ArrayList<>(); 
public RecyclerView mRecyclerView; 

private class MyViewHolder extends RecyclerView.ViewHolder { 

    public ImageView mTitle; 

    public MyViewHolder(View pItem) { 
     super(pItem); 

     mTitle = (ImageView) pItem.findViewById(R.id.imageView); 
    } 
} 

public MyAdapter(ArrayList<Article> pArticles, RecyclerView pRecyclerView) { 
    mArticles = pArticles; 
    mRecyclerView = pRecyclerView; 
} 

@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) { 
      View view = LayoutInflater.from(viewGroup.getContext()) 
      .inflate(R.layout.article_layout_allcats, viewGroup, false); 

     view.setOnClickListener(new View.OnClickListener() { 
     @Override 
    public void onClick(View v) { 
      mySound = MediaPlayer.create(v.getContext(), Article.getSounds()); 
      mySound.start(); 
     } 
    }); 

    return new MyViewHolder(view); 
} 

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) { 
    // uzupełniamy layout artykułu 
    Article article = mArticles.get(i); 
    ((MyViewHolder) viewHolder).mTitle.setImageResource(article.getTitle()); 
} 

@Override 
public int getItemCount() { 
    return mArticles.size(); 

} 

而且

public class Article { 
private int mTitle; 
public static int mSounds; 

private static int[] sTitles = { 
PAWEL int[] sTitles ={ 
     R.drawable.photo1, 
     ... 
     R.drawable.photo10 
}; 

public static int[] sSounds = { 
     R.raw.sound1, 
     ... 
     R.raw.sound10 

     }; 

public Article() { 

    Random random = new Random(); 

    mTitle = sTitles[random.nextInt(sTitles.length)]; 
    mSounds = sSounds[random.nextInt(sSounds.length)]; 
} 
public int getTitle() { 
    return mTitle; 

} 
public static int getSounds() { 
    return mSounds; 

} 
} 

回答

0

可能是因爲setOnClickListeneronCreateViewHolder

使用onBindViewHolder方法來獲取setOnClickListenerRecyclerView整行:

變化MyViewHolder讓行根查看:

public View view; 
public MyViewHolder(View pItem) { 
     super(pItem); 

     this.view=pItem; 
     .... 
    } 

2.現在添加click偵聽viewonBindViewHolder

View rowView=((MyViewHolder)viewHolder).view; 
rowView.setTag(article.getSounds()); // set sound it here 
view.setOnClickListener(new View.OnClickListener() { 
     @Override 
    public void onClick(View v) { 
      mySound = MediaPlayer.create(v.getContext(), 
        (Integer.parseInt(v.getTag().toString()))); 
      mySound.start(); 
     } 
}); 
+0

感謝您的回覆,但它對我無效。 – Pawel

+0

@Pawel:問題是否解決? –