Search code examples
androidandroid-fragmentsactionbarsherlockshareactionprovider

ShareActionProvider refresh text


I have an EditText which is initially filled with text from the local db. When the user leaves the screen (onPause), the updated text is stored in the local db. I also have a ShareActionProvider (using ActionBarSherlock).

When the user uses the ShareActionProvider, the old text is send to the target application. How can I refresh the text send through the actionprovider when the user presses the menu-item?

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.share_action_provider, menu);
    MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
    mActionProvider = (ShareActionProvider) actionItem.getActionProvider();
    mActionProvider.setShareIntent(createShareIntent());
}

private Intent createShareIntent() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, editText.getText().toString());
    return shareIntent;
}

It seems onOptionsItemSelected() is not called when the user presses the menu-item. So I tried the following onPause(), without luck:

@Override
public void onPause() {
    super.onPause();
    mActionProvider.setShareIntent(createShareIntent());
    // save to db:
    getActivity().saveText(editText.getText().toString());
}

BTW: This code is all in a Fragment.


Solution

  • Perhaps a bit overkill, but I got it working by setting the share Intent every time the EditText field is changed. I added a TextWatcher listener:

        editText.addTextChangedListener(new TextWatcher(){
            @Override
            public void afterTextChanged(Editable s) {
                 if(mActionProvider!=null) {
                        mActionProvider.setShareIntent(createShareIntent());
                 }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }});