【问题标题】:Add Button to Custom View将按钮添加到自定义视图
【发布时间】:2016-10-31 18:38:01
【问题描述】:

我尝试扩展 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 构造函数正在调用新的 TouchEventView()?这不对……
  • 是的,你是对的。我已经修好了谢谢。

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


【解决方案1】:

问题是您正在创建一个新的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);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-29
    • 2019-01-06
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多