分享按钮在Android

时间:2017-07-25 11:45:30

标签: android listview fragment share

我有ListView并且在其BaseAdapter中我想要弹出菜单,其中一个项目是“共享”项目,因此当用户点击它时,将弹出一个共享窗口/对话框:

这是我的弹出菜单是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

        }
    });

这就是我试图打开共享窗口/对话框的方式,它不会打开共享窗口/对话框,但是我点击弹出菜单中“共享”项目的toast显示:< / p>

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的一个片段内。

此外,我尝试了我创建的ShareAction()方法的exect代码,它在没有片段的活动中完美地工作,这就是为什么它在这里不起作用的奇怪......

2 个答案:

答案 0 :(得分:0)

尝试此操作以显示共享对话框

public void shareApp(Context context)
    {
        final String appPackageName = context.getPackageName();
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Check out yourAppName at: https://play.google.com/store/apps/details?id=" + appPackageName + refercode);//If you have refer code you can give
        sendIntent.setType("text/plain");
        context.startActivity(Intent.createChooser(sendIntent, "Share with..."));
    }

答案 1 :(得分:0)

从您的编码中删除此代码,

  if (null == mainActivity) {
     mainActivity = (MainActivity) context;
  }

并匹配if this like,

 if (item.getTitle().equals( "share")) {
                    mainActivity.shareAction();
                    return true;
                }