将按钮添加到自定义视图

时间:2016-10-31 18:38:01

标签: java android android-layout android-custom-view android-button

我尝试过LinearLayout而不是简单View来添加View的按钮和工作孩子,但我仍然没有得到任何输出。从概念上讲,我在某处错了。

public class TouchEventView extends LinearLayout {

    private Paint paint = new Paint();
    private Path path = new Path();
    private ViewGroup viewGroup;

    public TouchEventView(Context ctx) {
        super(ctx);

        //Button Code Starts Here
        LinearLayout touch = new TouchEventView(ctx);
        Button bt = new Button(ctx);
        bt.setText("A Button");
        bt.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        touch.addView(bt); //Button Not Working
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5f);
        this.setBackgroundColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawPath(path,paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float xPos = event.getX();
        float yPos = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                path.moveTo(xPos,yPos);
                return true;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(xPos,yPos);
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                return false;
        }

        invalidate();
        return true;
    }

}

1 个答案:

答案 0 :(得分:2)

问题是您要创建新的TouchEventView并将Button添加到View。相反,您应该将Button直接添加到当前View

如果您希望能够从XML获取任何属性,还应该从LinearLayout实现其他构造函数。

public class TouchEventView extends LinearLayout {

    public TouchEventView(Context context) {
        this(context, null);
    }

    public TouchEventView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouchEventView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Button button = new Button(getContext());
        button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        addView(button);
    }

}