ShareActionProvider not clickable and not rendering properly on first render

前端 未结 4 756
無奈伤痛
無奈伤痛 2021-02-08 10:10

I have a ShareActionProvider together with some other options in my ActionBar. It seems however that the ShareActionProvider has problems rendering properly when first rendered

4条回答
  •  青春惊慌失措
    2021-02-08 10:28

    That's because you have to add an intent to the ShareActionPRovider right after you inflate the menu, on onCreateOptionsMenu.

    If you do that only in onPrepareOptionsMenu, you'll have to manually call invalidateOptionsMenu() to trigger an ActionBar update (as the chosen answer tells you to). But that's not the way to do it.

    It works fine when the configuration changes, because onPrepareOptionsMenu() is called, and then your share button will work, since it now has an Intent.

    To fix that, just do something like this:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        getSupportMenuInflater().inflate(R.menu.YOUR_MENU_XML, menu);
    
        ShareActionProvider provider = (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider();
    
        if (provider != null) {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.putExtra(Intent.EXTRA_TEXT, YOUR_TEXT);
            shareIntent.setType("text/plain");
            provider.setShareIntent(shareIntent);
        }
    
        return true;
    }
    

    This way, the ShareActionProvider will have an Intent from the beginning, and will work as expected.

提交回复
热议问题