Android - Extended WebView class causing ClassCastException on Initialization

自古美人都是妖i 提交于 2020-01-02 05:14:12

问题


My problem is really straight forward. I can't seem to figure out why it's throwing an error of this kind (to add, I've never really used Java but have to for a simple android app now).

In my activity class I declare:

private MyWebView web;

Inside the 'onCreate' method I do this:

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

The class 'MyWebView' looks like this:

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) {
    }
}

This throws an a 'ClassCastException' with detailMessage = "android.webkit.WebView.

I'd really appreciate some help.

Thanks


回答1:


you have to name your custom WebView like this in your layout:

<yourpackagename.MyWebView
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
 />

yourpackagename: is the name of the package in wich you decalred your MyWebView Class




回答2:


the name in the layout was the one thing which was wrong. After I tried it again it errored again, but this time it triggered a 'MethodNotFoundException'. It seems like you have to implement this constrcutor

MyWebView(Context context, AttributeSet attrs)

instead of this one

MyWebView(Context context, AttributeSet attrs, int defStyle)

like eclipse suggests...



来源:https://stackoverflow.com/questions/10920757/android-extended-webview-class-causing-classcastexception-on-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!