Android自定义视图问题

时间:2011-05-26 11:33:34

标签: android view

嗨,大家好我一直在与这个问题作斗争,不知道是什么原因。我有一个简单的布局如下 <?xml version="1.0" encoding="utf-8"?> <view xmlns:android="http://schemas.android.com/apk/res/android" class="com.dinash.notepad.NotePade$LinedEditText" />

,活动类如下:

public class NotePade extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

public class LinedEditText extends EditText {
    private Rect mRect;
    private Paint mPaint;
    // we need this constructor for LayoutInflater
    public LinedEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRect = new Rect();
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        // mPaint.setColor(R.color.edit_note_line); //SET YOUR OWN COLOR
        // HERE
        mPaint.setColor(Color.RED); // SET YOUR OWN COLOR HERE
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // int count = getLineCount();
        int height = getHeight();
        // int height = 100;
        int line_height = getLineHeight();
        int count = height / line_height;
        if (getLineCount() > count)
            count = getLineCount();// for long text with scrolling

        Rect r = mRect;
        Paint paint = mPaint;
        int baseline = getLineBounds(0, r);// first line
        for (int i = 0; i < count; i++) {
            canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1,
                    paint);
            baseline += getLineHeight();// next line
        }
        super.onDraw(canvas);
    }
}

}

当我启动应用程序时,我一直收到此错误05-26 11:31:21.604: ERROR/AndroidRuntime(1537): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class com.dinash.notepad.NotePade$LinedEditText

并遵循

05-26 11:31:21.604: ERROR/AndroidRuntime(1537): Caused by: java.lang.NoSuchMethodException: LinedEditText(Context,AttributeSet)

任何机构都能解决问题所在...... 提前致谢

3 个答案:

答案 0 :(得分:4)

你需要让你的内部类静态。否则,它总是需要一个NotePade实例来为它提供一个初始化上下文。

here

答案 1 :(得分:1)

将自定义视图移动到单独的文件中。

答案 2 :(得分:1)

我认为在一个单独的类中编写自定义视图,您的布局应该是这样的......

<com.dinash.notepad.LinedEditText></com.dinash.notepad.LinedEditText>