我使用 eclipse 创建了一个 android 项目。默认的系统生成代码如下所示
package com.rmycustomclass.bengler;
import android.app.Activity;
import android.os.Bundle;
public class RMyCustomClassActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
我想尝试一个简单的自定义控件,所以我将代码更改如下。当我在网上搜索以创建一个简单的自定义控件时,会提到“通过子类化视图来创建类”。所以通过修改代码尝试如下。但它没有运行并且总是强制关闭。
package com.rmycustomclass.bengler;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class RMyCustomClassActivity extends View {
private Paint myPaint;
public RMyCustomClassActivity(Context cxt, AttributeSet attribute){
super(cxt,attribute);
init();
}
public RMyCustomClassActivity(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
public void init(){
myPaint = new Paint();
myPaint.setTextSize(12);
myPaint.setColor(0xFF668800);
myPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawText("TEEEST", 100, 100, myPaint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.setMeasuredDimension(150,200);
}
}
下面是我的xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:text="Enter text"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tableLayout1">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_weight="1">
</Button>
<Button android:layout_width="wrap_content" android:id="@+id/button1" android:layout_height="40dip" android:text="My button" android:layout_weight="1"></Button>
<test.control
android:id="@+id/control"
android:layout_height="match_parent"> </test.control>
</TableLayout>
</LinearLayout>