2016-03-16 5 views
0
  • У меня есть пользовательское listview, которое заполняет список слов из базы данных sqli.
    • В каждом элементе списка у меня есть кнопка воспроизведения изображения, чтобы воспроизвести аудиофайл для этого конкретного элемента списка.
    • Я использовал пользовательский ListView с адаптером массива.
    • В этом адаптере я написал событие setOnClick для этого изображения для воспроизведения звука.
    • Он отлично работает.

Но проблема при воспроизведении аудио, если кто-нибудь нажать на другую деятельность звук не прекращается.Android Custom ListView OnClick даже на изображении из пользовательского адаптера

вот моя деятельность класса

public class WordActivity extends ActionBarActivity { 

    categories category_obj; 
    word word_obj; 
    wordDB wordDb; 
    ViewFlipper viewFlipper; 

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

     TextView txt = (TextView) findViewById(R.id.phraseListHeading); 
     Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf"); 

     String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase(); 
     category_obj = (categories) getIntent().getSerializableExtra("category_obj"); 

     txt.setTypeface(font); 
     txt.setText(categoryName); 


     ListView wordListView; 
     wordListView = (ListView)findViewById(R.id.list_view_word); 
     wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       Object o = parent.getItemAtPosition(position); 
       word_obj = (word) o; 
       if(Integer.valueOf(word_obj.getCategoryId())>=0) { 
        Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class); 
        myIntent.putExtra("word_obj", word_obj); 
        myIntent.putExtra("position",position); 
        myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString()); 
        myIntent.putExtra("favouriteFlag",0); 
        myIntent.putExtra("searchFlag",0); 
        myIntent.putExtra("searchString", ""); 
        WordActivity.this.startActivity(myIntent); 

       } 

      } 
     }); 


    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_word, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    protected void onResume(){ 
     super.onResume(); 



     GlobalState state = ((GlobalState) getApplicationContext()); 
     state.doAction(); 

     wordDb = new wordDB(WordActivity.this); 
     getAllWords(); 



    } 

    public void getAllWords(){ 

     ArrayList<word> words = new ArrayList<word>(); 
     category_obj = (categories) getIntent().getSerializableExtra("category_obj"); 
     Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString()); 
     words.add(new word("-1","-1","","","","","","","x.mp3","")); 
     words.add(new word("-2","-2","","","","","","","x.mp3","")); 
     row.moveToFirst(); 
     while (!row.isAfterLast()) { 
      //Log.d("Data id: ", row.getString(2)); 

      words.add(new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9))); 
      row.moveToNext(); 
     } 
     row.close(); 

     WordAdapter adapter = new WordAdapter(WordActivity.this, words); 

     ListView listView = (ListView) findViewById(R.id.list_view_word); 
     listView.setAdapter(adapter); 



    } 


} 

вот мой адаптер класса

class WordAdapter extends ArrayAdapter { 

    ArrayList<word> words = new ArrayList<word>(); 
    private Context mContext; 
    MediaPlayer mediaPlayer; 


    public WordAdapter(Context context, ArrayList<word> list) { 
     super(context, R.layout.words_list, list); 
     mContext = context; 
     words = list; 
    } 



    public View getView(int position, View convertView, final ViewGroup parent) { 

     View view; 


     if (convertView == null) { 
      LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      view = inflater.inflate(R.layout.words_list, null); 

      TextView txt = (TextView) view.findViewById(R.id.list_view_words); 
      TextView txt2 = (TextView) view.findViewById(R.id.translated_text); 
      TextView txt3 = (TextView) view.findViewById(R.id.pronounce); 
      Typeface font = Typeface.createFromAsset(mContext.getAssets(), "fonts/NotoSans-Regular.ttf"); 
      txt.setTypeface(font); 
      txt2.setTypeface(font); 
      txt3.setTypeface(font); 
     } 
     else { 
      view = convertView; 
     } 

     if(Integer.valueOf(words.get(position).getCsvWordId())>=0) { 
      View divbottom = (View) view.findViewById(R.id.phrase_list_bottom_divider); 
      divbottom.setVisibility(View.VISIBLE); 

      ImageView playAudio = (ImageView) view.findViewById(R.id.phraselist_play_audio); 
      playAudio.setVisibility(View.VISIBLE); 



     } else { 
      View divbottom = (View) view.findViewById(R.id.phrase_list_bottom_divider); 
      divbottom.setVisibility(View.GONE); 


      ImageView playAudio = (ImageView) view.findViewById(R.id.phraselist_play_audio); 
      playAudio.setVisibility(View.GONE); 



     } 



     TextView contactNameView = (TextView) view.findViewById(R.id.list_view_words); 
     Integer mainTextlen = words.get(position).getMainText().length(); 
     contactNameView.setText(words.get(position).getMainText()); 
     if(mainTextlen > 40) 
     { 
      TextView txt = (TextView) view.findViewById(R.id.list_view_words); 
      txt.setTextSize(14); 
     } 

     TextView translatedText = (TextView) view.findViewById(R.id.translated_text); 
     translatedText.setText(words.get(position).getTranslationText()); 

     Integer transTextlen = words.get(position).getTranslationText().length(); 
     if(transTextlen > 40) 
     { 
      TextView txt2 = (TextView) view.findViewById(R.id.translated_text); 
      txt2.setTextSize(14); 
     } 

     TextView pronounceText = (TextView) view.findViewById(R.id.pronounce); 
     pronounceText.setText(words.get(position).getPronunciation_in_english()); 

     Integer pronounceTextlen = words.get(position).getPronunciation_in_english().length(); 
     if(pronounceTextlen > 40) 
     { 
      TextView txt3 = (TextView) view.findViewById(R.id.pronounce); 
      txt3.setTextSize(12); 
     } 

     /*get full sound file name*/ 

     Integer fileNameLength = words.get(position).getAudio().toString().length(); 
     String fileName = words.get(position).getAudio().toString(); 
     final String soundFile = fileName.substring(0, fileNameLength - 4); 
     final ImageView imgPlay = (ImageView) view.findViewById(R.id.phraselist_play_audio); 


     imgPlay.setOnClickListener(new View.OnClickListener() { 
      @Override 

      public void onClick(View v) { 

       View parentRow = (View) v.getParent(); 
       ListView listView = (ListView) parentRow.getParent(); 

       if(mediaPlayer == null) { 

        final int position = listView.getPositionForView(parentRow); 

        try { 
         Uri mp3 = Uri.parse("android.resource://" + mContext.getPackageName() + "/raw/" + soundFile); 
         mediaPlayer = new MediaPlayer(); 
         mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
         mediaPlayer.setDataSource(mContext, mp3); 
         mediaPlayer.prepare(); // might take long! (for buffering, etc) 
         mediaPlayer.start(); 
         imgPlay.setImageResource(R.drawable.playactive); 
         // mediaPlayer.setOnCompletionListener(onCompletionListener); 
         mediaPlayer.setOnCompletionListener(new OnCompletionListener() { 
          @Override 
          public void onCompletion(MediaPlayer mp) { 
           mediaPlayer.release(); 
           mediaPlayer = null; 
           imgPlay.setImageResource(R.drawable.playinactive); 
          } 
         }); 
        } catch (IllegalArgumentException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } catch (SecurityException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } catch (IllegalStateException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 




      } 




     }); 


     return view; 
    } 




} 
+0

делают медиапроигрыватель глобальные и перед игрой сначала проверьте, является ли mediaPlayer.isPlaying истинным или ложным. Если true, сначала остановите этот звук, а затем выполните требуемую работу. –

+0

Объект mediaplayer находится в классе адаптера. Итак, в основном, как проверить его в классе Activity. – Parangan

+0

Вы пытались установить 'mediaPlayer = null' непосредственно внутри' onClick' –

ответ

1

Но проблема при воспроизведении аудио, если кто-то нажмите на другой деятельности звук не стоп

Создать геттер в WordAdapter которые возвращают текущую игру MediaPlayer экземпляра и вызвать его в onItemClick перед началом следующего действия, как:

public MediaPlayer getMPlayerInstace(){ 
    return this.mediaPlayer; 
} 

Позовите stop метод onItemClick:

MediaPlayer mPlayer; 
mPlayer=adapter.getMPlayerInstace(); 
if(mPlayer!=null){ 
    mPlayer.stop(); 
    mPlayer.release(); 
} 
+0

, это здорово. Спасибо. – Parangan

Смежные вопросы