Trying to display url in Web View

2019-07-15 03:24发布

问题:

I am experimenting with the loopj package. I am trying to make a HTTP request to a website and display the website in the webview.

I am successfully getting a result back, however the web view does not display the page as desired, instead chrome opens up and displays the page.

Am I missing something or is there a way I can override this unwanted behaviour?

Below is my oncreate method where I am making the request:

public class MainActivity extends Activity {

Button connectBtn;
TextView status;
WebView display;
String url = "http://www.google.com";
AsyncHttpClient client;

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

    status = (TextView)findViewById(R.id.statusbox);
    connectBtn = (Button)findViewById(R.id.connectBtn);
    display = (WebView)findViewById(R.id.webView1);

    connectBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            client = new AsyncHttpClient();
            client.get(url, new AsyncHttpResponseHandler(){

                @Override
                public void onSuccess(String response) {
                    Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
                    display.loadUrl(url);

                }
            });
        }
    });
}

回答1:

setWebViewClient to your WebView and override shouldOverrideUrlLoading() now write view.loadUrl(url); in that method.

Just add this code,

display.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
          view.loadUrl(url);
          return true;
}}); 


回答2:

You need to set a WebViewClient and override the shouldOverrideUrlLoading method. Something like this:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
        view.loadUrl(url);
    }
});

That makes sure that clicks on links in the WebView are handled by the WebView itself.


Edit: Actually, I misread the question. You aren't dealing with a click in the WebView itself, so this isn't relevant. Sorry!



回答3:

just use this code under you webviewclient

public void onPageFinished(WebView view, String url) {  
    super.onPageFinished(view, url);
    final EditText editText = (EditText) findViewById(R.id.urlfield);           
    editText.setText(url);

} 

}