我正在尝试在android中制作自定义视图我在MainActivity和XML文件中提到了我的所有arrtrs列表,但我在main.xml
中出错:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews.piechart"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.customviews.charting.piechart.MainActivity
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
custom:titleText="Background color"
custom:valueColor="@android:color/holo_green_light"
/>
</LinearLayout>
答案 0 :(得分:0)
你有没有参数的构造函数吗?
您应该添加如下构造函数:
public MainActivity(Context context, AttributeSet attrs) {
super(context, attrs);
}
或
public MainActivity(Context context) {
super(context);
}
您要求提供一个自定义视图的简单示例:
public class BirdView extends ImageView {
private float direction = 0;
Paint paint = new Paint();
public BirdView(Context context) {
super(context);
}
public BirdView(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(6);
}
public BirdView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}
@Override
public void draw(Canvas canvas) {
canvas.save();
int stratX = getWidth() / 2;
int startY = getHeight() / 2;
canvas.rotate(direction, stratX, startY);
super.draw(canvas);
canvas.restore();
canvas.drawLine(stratX, startY, stratX, startY + 80, paint);
}
public void update(float dir) {
direction = dir;
invalidate();
}
}