Android - 扩展的WebView类在初始化时导致ClassCastException

Ke *_*Vin 4 java android webview

我的问题非常直截了当.我似乎无法弄清楚为什么它会抛出这种错误(补充一点,我从来没有真正使用过Java,但现在必须使用简单的Android应用程序).

在我的活动课中,我声明:

private MyWebView web;
Run Code Online (Sandbox Code Playgroud)

在'onCreate'方法中,我这样做:

try {
    web = (MyWebView)findViewById(R.id.webview);
}
catch(Exception e) {
    Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT);
}
Run Code Online (Sandbox Code Playgroud)

"MyWebView"类看起来像这样:

import android.app.AlertDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;


public class MyWebView extends WebView {
    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
    }
}
Run Code Online (Sandbox Code Playgroud)

这将使用detailMessage ="android.webkit.WebView抛出'ClassCastException'.

我真的很感激一些帮助.

谢谢

Ke *_*Vin 13

布局中的名称是错误的一件事.我再次尝试后再次出错,但这次它触发了'MethodNotFoundException'.看来你必须实施这个建设者

MyWebView(Context context, AttributeSet attrs)
Run Code Online (Sandbox Code Playgroud)

而不是这一个

MyWebView(Context context, AttributeSet attrs, int defStyle)
Run Code Online (Sandbox Code Playgroud)

喜欢eclipse建议......


K_A*_*nas 10

您必须在布局中将自定义WebView命名为:

<yourpackagename.MyWebView
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
 />
Run Code Online (Sandbox Code Playgroud)

yourpackagename:是您对MyWebView类进行十分转换的软件包的名称