单击更改ActionBar菜单项图标

时间:2015-01-06 13:41:53

标签: java android android-actionbar

我希望我的操作栏菜单项图标从ic_action_mic更改为ic_action_micoff,反之亦然。我的代码有效,但并非总是如此。

 @Override
    protected boolean onPrepareOptionsPanel(View view, Menu menu) {
       if(tempItem!=null && tts!=null) {
           if (tts.isSpeaking())
               tempItem.setIcon(getResources().getDrawable(R.drawable.ic_action_micoff));
           else
               tempItem.setIcon(getResources().getDrawable(R.drawable.ic_action_mic));
       }
        return super.onPrepareOptionsPanel(view, menu);
    }

    TextToSpeech tts;
    @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_read)
        {

            if(tts != null)
                if(tts.isSpeaking())
                {
                    tts.stop();
                    invalidateOptionsMenu();
                    return true;
                }

            //read the whole news
            tts = new TextToSpeech(newsActivity.this, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int status) {
                    invalidateOptionsMenu();

                    if(status == TextToSpeech.SUCCESS)
                    {
                        TextView txtNews = (TextView)findViewById(R.id.textViewNewsDescription);
                        String readableText = txtNews.getText().toString();
                        tts.setLanguage(Locale.US);
                        tts.setSpeechRate(.85f);
                        //tts.speak("Hi!", TextToSpeech.QUEUE_FLUSH, null);
                        tts.speak(readableText ,TextToSpeech.QUEUE_FLUSH, null);
                        invalidateOptionsMenu();
                    }
                }
            });


        }

        return super.onOptionsItemSelected(item);
    }

请建议我如何实现我想要的目标。 TIA

0 个答案:

没有答案