Devrath
Devrath

Reputation: 42824

Creating button dynamically inside relative layout ontouch android

What I am doing: I am trying to create a button dynamically onTouch

What is Happening:

  1. I am able to create the button but the button is not created exactly in the place I touch, instead its little bit in the bottom right(might be adjustment of button in pixel).
  2. How can i make sure i create the button exactly in the same place i touch

 @Override
    public boolean onTouch(View v, MotionEvent event) {

        //Get the x & y co-ordinates from the event
        float x = event.getX();
        float y = event.getY();

        //Convert into Integer
        int mX = (int) x;
        int mY = (int) y;

        //Perform Event on touch of canvas
        performEventOnTouchOfCanvas(event, mX, mY);

        return true;
    }

private void performEventOnTouchOfCanvas(MotionEvent event,int mX, int mY) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                Point mPoint=new Point(mX,mY);
                createButton(mPoint.x,mPoint.y);
                break;

        }

    }

  private void createButton(float x, float y) {
        Button btn = new Button(ActDrawAreaTwo.this);
        RelativeLayout.LayoutParams bp = new RelativeLayout.LayoutParams(40, 40);
        bp.leftMargin = (int) x;
        bp.topMargin = (int) y;

        //Assign the Id to the button
        btn.setLayoutParams(bp);
        CommonFunctions.setBackgroundDrawable(btn, ActDrawAreaTwo.this, R.drawable.white_circle_dot);//Set Button Drawable

        String mTag=String.valueOf((int)x )+","+ String.valueOf((int) y);
        btn.setTag(mTag);
        canvasLayoutId.addView(btn);

    }

Note: canvasLayoutId is a relative layout

Upvotes: 0

Views: 74

Answers (1)

Orkun Kocyigit
Orkun Kocyigit

Reputation: 1147

Android start drawing from views topmost left side. So when you pass coordinates, it will assume those are topmost left side of the button. If you want your button to appear in the middle of where you touch you need to change your coordinates with these:

x = x + button_width / 2   
y = y + button_height / 2 

In Android default padding is also same button's border, so you can find button's width and height with using this:

button_width = mButton.getPaddingRight() - mButton.getPaddingLeft();
button_height = mButton.getPaddingBottom() - mButton.getPaddingTop();

You can also use button.getWidth() and button.getHeight() assuming you are not using MATCH_PARENT or WRAP_CONTENT as your paramters.

Upvotes: 1

Related Questions