1

I have a ViewPager, with each view being a WebView. I'd like, if the user clicks on a link in one of the WebViews, to set the title of the Actionbar to the current web page.

I was hoping I could use shouldOverrideUrlLoading to do that, but the page title is always the previous page. So if a user clicks on link 1, then link 2, and link 3. On page 3 the title of link 2 is being shown in the Actionbar.

If I put the title setting code in onPageFinished, the page title is being set to the next view of the ViewPager, due to the ViewPager executing the previous/next views for performance.

Fragment

public class Browser extends SherlockFragment {

    private OnBrowserSetTitle mBrowserSetTitle;

   @Override
    public void onAttach(Activity act) {
        super.onAttach(act);
        mBrowserSetTitle = (OnBrowserSetTitle)act;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        activity = getActivity();

        setHasOptionsMenu(true);

        mWebView = (WebView)getView().findViewById(R.id.webview);
        mWebView.loadUrl("http://www.google.com");

        mWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

            }

             @Override
             public boolean shouldOverrideUrlLoading(WebView view, String url) {
                  view.loadUrl(url);
                  if (view.getTitle() != null && view.getTitle().length() > 0)
                  {
                      mBrowserSetTitle.onBrowserSetTitle(mTitle);
                  }

                 return true;
             }            
        });
    }
}

Activity

public class BrowserPager extends SherlockFragmentActivity implements Interfaces.OnBrowserSetTitle {

    @Override
    public void onCreate(final Bundle icicle)
    {    
        super.onCreate(icicle);

        setContentView(R.layout.browser_pager);
    }

    @Override
    public void onBrowserSetTitle(String title) {
        getSupportActionBar().setTitle(title);
    }
}
4

1 回答 1

1

Change onBrowserSetTitle to have the following definition:

@Override
public void onBrowserSetTitle(String title, View view) {
    if (mViewPager.getCurrentItem() == mViewPager.getAdapter().getItemPosition(view)) {
        getSupportActionBar().setTitle(title);
    }
}

And then call onBrowserSetTitle from onPageFinished like so:

@Override
public void onPageFinished(WebView view, String url) {
    if (view.getTitle() != null && view.getTitle().length() > 0) {
        mBrowserSetTitle.onBrowserSetTitle(mTitle, view);
    }
}   
于 2013-03-31T00:56:04.177 回答