我有一个全局变量。在应用程序的工作期间,它会更改值。有一个共享按钮,当我点击它时,我只能分享应用程序启动时的值。我想通过shareIntent发送更新的值。怎么做?
private int counter;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterTextView = (TextView) findViewById(R.id.counter_text_view);
counter++;
String counterStr = Integer.toString(counter);
counterTextView.setText(counterStr);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
setShareIntent(createShareIntent());
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
counter);
return shareIntent;
}
答案 0 :(得分:1)
您可以使用SharedPreferences永久存储数据。
答案 1 :(得分:0)
您将常量文本字符串“counter”放入Intent
。也许尝试这样的事情:
shareIntent.putExtra("counter", counter);
然后像这样把它拿回来:
int counter = getIntent().getIntExtra("counter", -1);
if (counter != -1) {
// do stuff
}