Dev Yadav Dev Yadav - 1 month ago 15
Android Question

Add Button to Custom View

I've tried extending

LinearLayout
instead of simple
View
for adding buttons and working children of
View
but I am still not getting any output. Conceptually I'm wrong somewhere.

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;
}

}

Answer

The issue is that you are creating a new TouchEventView and adding the Button to that View. Instead you should add the Button directly to the current View.

You should also implement the other constructors from LinearLayout if you want to be able to get any attributes from XML.

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);
    }

}
Comments