我有ListView,在它的BaseAdapter中,我想有一个弹出菜单,其中一个项目是“共享”项目,因此当用户单击它时,将弹出一个共享窗口/对话框:
mViewHolder.optionMenuButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(context, mViewHolder.optionMenuButton);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.share_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(context,
"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();
if (item.getTitle() == "share") {
if (null == mainActivity) {
mainActivity = (MainActivity) context;
}
mainActivity.shareAction();
return true;
}
return false;
}
});
popup.show();//showing popup menu
}
});
这就是我试图打开共享窗口/对话框的方式,它并没有打开共享窗口/对话框,但我点击弹出菜单的“共享”项的祝酒词出现了:
public void shareAction() {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "You have to check this out: " + "https://www.google.com/";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Check this out");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
ShareAction()方法位于mainActivity中,适配器是ListView的BaseAdapter,此ListView位于mainActivity的一个片段中。