我正在尝试制作一个无效的简单自定义视图。我从布局资源文件中查看了自定义视图类。但它不起作用。谁能告诉我问题出在哪里。
public class WriteOnScreenActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
public class CustomView extends View {
private Paint paint;
public TouchEventView(Context context) {
super(context);
paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(25);
paint.setAntiAlias(true);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("Hello World", 5, 30, paint);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.touch.CustomView
android:id="@+id/TouchEventView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
答案 0 :(得分:0)
将TouchEventView类的定义移动到新文件中。
这是修复。
public class TouchEventView extends View {
private Paint paint;
public TouchEventView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup(context, attrs, defStyle);
}
public TouchEventView(Context context, AttributeSet attrs) {
super(context, attrs);
setup(context, attrs, 0);
}
public TouchEventView(Context context) {
super(context);
setup(context, null, 0);
}
private void setup(Context context, AttributeSet attrs, int defStyle)
{
paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(25);
paint.setAntiAlias(true);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText("Hello World", 5, 30, paint);
}
}