user1548172
user1548172

Reputation:

Android: WebView - open certain URLs inside WebView, the rest externally?

Here's my code:

public class MainActivity extends Activity {

@SuppressLint("SetJavaScriptEnabled") @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView mywebview = (WebView) findViewById(R.id.webview);
    mywebview.loadUrl("http://www.shufflemylife.com/shuffle");
    WebSettings webSettings = mywebview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mywebview.setWebViewClient(new WebViewClient());

}

class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("/shuffle")){
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
            }
        return true;

        }
    }
    }

Basically, I want any url containing '/shuffle' to load inside WebView, and anything else to be opened in the external browser. Is it doable? How close am I do accomplishing this?

Thanks for any help!

Upvotes: 5

Views: 8134

Answers (2)

Brad
Brad

Reputation: 9223

To clarify, this is how you should write your shouldOverrideUrlLoading method:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("/shuffle")) {
        mWebView.loadUrl(url);
        return false;
    } else {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
        return true;
    }
}

Upvotes: 4

CommonsWare
CommonsWare

Reputation: 1006574

Is it doable?

Yes.

How close am I do accomplishing this?

Close, but backwards. The default behavior of a WebView is to display links in the external browser. Hence, if url.contains("/shuffle"), you want to call loadUrl() on your WebView to keep the link internal, and return true in that case. If this is a URL you want handled normally, return false.

Upvotes: 3

Related Questions