2013-02-02 51 views
4

我想在WebView中接受用戶的任何頁面,並允許他們與FaceBook/etc共享URL作爲ACTION_SEND意圖。將URL從WebView傳遞給ShareActionProvider?

我試過這個,但顯然URL不存在於onCreateOptionsMenu。我如何將它移動到onOptionsItemsSelected?

private ShareActionProvider mShareActionProvider; 
@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // TODO Auto-generated method stub 


    return super.onOptionsItemSelected(item); 
} 
    @Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    MenuItem item = menu.findItem(R.id.menu_item_share); 
    mShareActionProvider = (ShareActionProvider)item.getActionProvider(); 
    mShareActionProvider.setShareHistoryFileName(
     ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME); 
    mShareActionProvider.setShareIntent(createShareIntent()); 
    return true; 
} 
private Intent createShareIntent() { 
     Intent shareIntent = new Intent(Intent.ACTION_SEND); 
      shareIntent.setType("text/plain"); 
      shareIntent.putExtra(Intent.EXTRA_TEXT, 
      web.getUrl()); 
      return shareIntent; 
     } 
+0

只是一個說明,我的意思是將它傳遞給onOptionsItemSelected,以便「url」將有一個值(頁面加載後) – wilxjcherokee

回答

7

上面的代碼不起作用,因爲onCreateOptionsMenu僅在第一次顯示選項菜單時被調用一次。

解決這個問題很簡單。當調用onOptionsItemSelected時,我們正在構建我們的意圖。這是當選擇充氣菜單的任何資源時。如果選擇的項目是共享資源,則執行shareURL,現在構建並啓動意圖。

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

@Override 
public final boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.menu_item_share: 
      shareURL(); 
    } 
    return super.onOptionsItemSelected(item); 
} 

private void shareURL() { 
    Intent shareIntent = new Intent(Intent.ACTION_SEND); 
    shareIntent.setType("text/plain"); 
    shareIntent.putExtra(Intent.EXTRA_TEXT, web.getUrl()); 
    startActivity(Intent.createChooser(shareIntent, "Share This!")); 
} 

我沒有測試上面的代碼示例。無論是在實際的設備上還是在Java編譯器中。不過,它應該可以幫助你解決你的問題。

+0

感謝您的答案!我明白你的意思,只是好奇底下的意圖是什麼?我需要在其他地方創建嗎?編輯:沒關係,它的工作非常感謝! – wilxjcherokee

+0

對不起,我的錯。 intent - > shareIntent – ottel142