使用自定义视图时findViewById中的ClassCastException

时间:2012-03-18 16:18:22

标签: android android-layout

我正在使用自定义TextView。但是当我使用Id的查找视图检索它时,我得到了ClassCastException。我在XML文件中使用它如下:

<View class="com.android.smsapp.MsgTextView" android:id="@+id/text"

并在像这样的java文件中使用它。

MsgTextView text = (MsgTextView) row.findViewById(R.id.text);

我做错了什么?


@Pavandroid

我已将其包含在正确的文件中

    package com.android.smsapp;

    import android.content.Context;
    import android.util.AttributeSet;
    import android.widget.TextView;

    public class MsgTextView extends TextView {
    private String sender;

    MsgTextView(Context c){
        super(c);
    }

    MsgTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    MsgTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setSender(String s) {
        sender = s;
    }

    public String getSender() {
        return (sender);
    }
}`

此外,当我正确检查时,LogCat再显示一行

03-19 14:30:41.476: E/AndroidRuntime(24089): Caused by: java.lang.NoSuchMethodException: MsgTextView(Context,AttributeSet).. But I have defined this constructor. 

1 个答案:

答案 0 :(得分:1)

而不是上面的代码使用下面的代码。

<com.android.smsapp.MsgTextView 
          android:id="@+id/text"
          additional parameters here....>
</com.android.smsapp.MsgTextView>