共享操作提供程序未显示

时间:2016-05-04 07:32:27

标签: java android xml menu

这是我的菜单资源文件

<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    android:orderInCategory="2"
    app:showAsAction="ifRoom"
    android:actionProviderClass="android.widget.ShareActionProvider">
 </item>
</menu>

这是我的java代码

public boolean onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.menu_main,menu);
    MenuItem menuItem = menu.findItem(R.id.action_share);
    shareActionProvider =(ShareActionProvider)menuItem.getActionProvider();
   // setIntent("COOL NIKS");
    return super.onCreateOptionsMenu(menu);
}

这不显示共享操作提供程序。我该如何解决?

1 个答案:

答案 0 :(得分:1)

以下是完整工作示例的样子。这使用AppCompat库。

您需要将http://schemas.android.com/apk/res-auto架构添加到菜单项XML。

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >
    <item
        android:id="@+id/action_share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        app:showAsAction="always"
        android:title="Share" />
</menu>

现在,您必须更新MainActivity以使用ShareActionProvider

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {
    private ShareActionProvider mShareActionProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        // Get the menu item.
        MenuItem menuItem = menu.findItem(R.id.action_share);
        // Get the provider and hold onto it to set/change the share intent.
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
        // Set share Intent.
        // Note: You can set the share Intent afterwords if you don't want to set it right now.
        mShareActionProvider.setShareIntent(createShareIntent());
        return true;
    }

    // Create and return the Share Intent
    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "http://google.com");
        return shareIntent;
    }

    // Sets new share Intent.
    // Use this method to change or set Share Intent in your Activity Lifecycle.
    private void changeShareIntent(Intent shareIntent) {
        mShareActionProvider.setShareIntent(shareIntent);
    }
}