即使是来自自定义适配器的图像,Android Custom ListView OnClick也是如此

时间:2016-03-16 05:51:38

标签: java android listview

  • 我有一个自定义列表视图,用于填充sqli数据库中的单词列表。
    • 在每个列表项中,我都有一个播放图像按钮,用于播放该特定列表项的音频文件。
    • 我使用了带有数组适配器的Custom ListView。
    • 在该适配器中,我为该图像编写了setOnClick事件以播放音频。
    • 工作正常。

但问题是在播放音频时如果有人点击其他活动声音不会停止。

这是我的活动类

 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;
    }




}

1 个答案:

答案 0 :(得分:1)

  

但问题是在播放音频时,如果有人点击其他人   活动声音不会停止

WordAdapter中创建一个getter方法,返回当前正在播放的MediaPlayer实例并在开始下一个Activity之前在onItemClick内调用它:

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

现在在stop中调用onItemClick方法:

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