package com.example.ch_m_usman.example;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView; public class MainActivity extends AppCompatActivity {
private ShareActionProvider actionProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String msg = getIntent().getStringExtra("key");
if (msg != null){
TextView tv = (TextView) findViewById(R.id.msgdisplay);
tv.setText(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.share_action);
actionProvider = (ShareActionProvider) menuItem.getActionProvider();//here i got error
return super.onCreateOptionsMenu(menu);
}
private void setIntent(String text){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,text);
actionProvider.setShareIntent(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
String msg = "Welcome to Second Activity";
intent.putExtra("msg", msg);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
我建议采用不同的方法来解决这个问题。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
并添加:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.share_action) {
startShareIntent();
}
return super.onOptionsItemSelected(item);
}
并且:
@Override
public void startShareIntent(String link) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, link);
startActivity(Intent.createChooser(intent, getString(R.string.share)));
}
几乎不言自明。这样,您可以在单击共享按钮后更好地控制行为。