簡體   English   中英

將按鈕添加到自定義視圖

[英]Add Button to Custom View

我嘗試擴展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;
    }

}

問題是您要創建一個新的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);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM