簡體   English   中英

無法將android.support.v4.view.MenuItemCompat轉換為android.widget.ShareActionProvider

[英]Cannot cast android.support.v4.view.MenuItemCompat to android.widget.ShareActionProvider

我目前正在使用在線教程學習android,該教程可以在http://www.raywenderlich.com/78576/android-tutorial-for-beginners-part-2中找到

到目前為止,一切進展順利,但是我現在遇到了一些問題,即使我的代碼與本教程的代碼匹配,我仍然收到上面的錯誤消息(該線程的標題)。

我的進口如下...

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import  android.widget.ShareActionProvider;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Button;

我在if語句中遇到以下問題...

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu.
    // Adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    // Access the Share Item defined in menu XML
    MenuItem shareItem = menu.findItem(R.id.menu_item_share);

    // Access the object responsible for
    // putting together the sharing submenu
    if (shareItem != null) {
        mShareActionProvider =  (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
    }

    // Create an Intent to share your content
    setShareIntent();

    return true;
}

private void setShareIntent() {

    if (mShareActionProvider != null) {

        // create an Intent with the contents of the TextView
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development");
        shareIntent.putExtra(Intent.EXTRA_TEXT, mainTextView.getText());

        // Make sure the provider knows
        // it should work with that Intent
        mShareActionProvider.setShareIntent(shareIntent);
    }
}

我以為這可能是由於最近的更新導致一些代碼過時了,但我並沒有太多想法,因為我對android並不了解。

謝謝您的幫助

您需要從支持庫導入ShareActionProvider,如下所示:

import android.support.v7.widget.ShareActionProvider;

由於您支持較舊的Android版本,並且使用MenuItemCompat的支持庫實現,因此,如果可用,還需要使用與之交互的其他類的支持版本。 使用自動導入時需要注意,如果提供選擇,請選擇支持版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM