2012-10-23 147 views
1

我已經在單一佈局中創建了edittext和go按鈕以及webview。當一個人輸入一個url並點擊go按鈕時,webview應該加載網站內容,而不是默認瀏覽器來加載網站我該如何解決這個問題?如何在同一頁面加載WebView

這是我的代碼

xml文件

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" > 

<WebView 
    android:id="@+id/webview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_marginTop="50dip" /> 


<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    > 

    <EditText 
     android:id="@+id/etenterurl" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1.0" 
     android:inputType="textUri" /> 

    <Button 
     android:id="@+id/buttongo" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="3.0" 
     android:text="Go" /> 
</LinearLayout> 


</FrameLayout> 

java代碼:

import java.util.ArrayList; 

import android.os.Bundle; 
import android.view.View; 
import android.webkit.WebView; 
import android.widget.Button; 
import android.widget.EditText; 
import android.annotation.SuppressLint; 
import android.app.Activity; 


public class MainActivity extends Activity { 
EditText etenter; 
Button bgo; 
WebView webview; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    etenter= (EditText)findViewById(R.id.etenterurl); 
    bgo =(Button)findViewById(R.id.buttongo); 
    webview = (WebView)findViewById(R.id.webview); 
    bgo.setOnClickListener(new View.OnClickListener() { 

     @SuppressLint("SetJavaScriptEnabled") 
     @Override 
     public void onClick(View v) { 
      String url=etenter.getText().toString(); 
      if(url.trim().length()>0){ 
       webview.getSettings().setJavaScriptEnabled(true); 
       webview.loadUrl("http://"+url); 

      } 

     } 
    }); 


} 

}

+0

你可以發佈你的代碼.. – Nermeen

回答

4

你必須使用WebViewClient

wbView.setWebViewClient(new MyWebViewClient()); 

    private class MyWebViewClient extends WebViewClient { 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) 
    { 
     Log.v("uuuurl",url); 
     view.loadUrl(url); 
     return true; 
    } 
} 

See here例如

+0

它的工作,我有一個問題,多給IM作爲50dp寬線性佈局和50dp爲paddingTop for webview,但webview不會相應地對齊。 – Anirudh

+0

路徑和錯誤:)。通過在高度和寬度上進行更改 – Abhi

+0

嘗試了很多,完全沒有工作 – Anirudh

2

你應該使用WebViewClient

webview.setWebViewClient(new WebViewClient(){ 

      @Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 

       Log.d("TAG", " ==> "+url); 
       view.loadUrl(url); 
       return true;     
      } 

     }); 
相關問題