2013-02-26 23 views
4

我從我的佈局得到WebView有沒有辦法來重寫WebView的行爲?

 WebView webView = (WebView) rootView.findViewById(R.id.myWebView); 

我要重寫的onKeyDown行爲。 通常,我可以通過子類覆蓋它。

 WebView webView = new WebView(this) { 

     @Override 
     public boolean onKeyDown (int keyCode, KeyEvent event) { 
     // Do my stuff.... 
     } 
} 

然而,由於我使用findViewById拿到的WebView,是有沒有辦法覆蓋的方法?

P.S:它實際上是一個更復雜的情況下,我不能在MainActivity覆蓋onKeyDown,因爲它調用WebViewonKeyDown第一。

回答

6

如果要覆蓋某些方法,你必須創建一個自定義WebViewextends WebView

這將是這個樣子:

public class CustomWebView extends WebView { 

    public CustomWebView(Context context) { 
     this(context, null); 
    } 

    public CustomWebView(Context context, AttributeSet attrs) { 
     this(context, attrs, 0); 
    } 

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     /* any initialisation work here */ 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     /* your code here */ 
     return super.onKeyDown(keyCode, event); 
    } 

} 

對於這個工作,你必須相應地改變你的XML佈局文件:

<com.example.stackoverflow.CustomWebView 
    android:id="@+id/webview" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

而且,當你膨脹的WebView,使確定您正在將其轉換爲CustomWebView的正確類型。

CustomWebView webView = (CustomWebView) findViewById(R.id.webview); 

否則,您將得到一個java.lang.ClassCastException

相關問題