我在做什么: 我正在尝试动态创建onTouch
按钮发生了什么:
@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);
}
注意:canvasLayoutId是相对布局
答案 0 :(得分:1)
Android从视图最左侧开始绘制。因此,当您传递坐标时,它将假设这些是按钮的最左侧。如果您希望按钮显示在您触摸的位置的中间,则需要使用以下内容更改坐标:
<div id="a1">Hi</div>
<div>Some Random Text</div>
<div id="a2">Hello</div>
在Android中,默认填充也是按钮的边框,因此您可以使用以下功能找到按钮的宽度和高度:
x = x + button_width / 2
y = y + button_height / 2
如果您没有使用button_width = mButton.getPaddingRight() - mButton.getPaddingLeft();
button_height = mButton.getPaddingBottom() - mButton.getPaddingTop();
或button.getWidth()
作为参数,也可以使用button.getHeight()
和MATCH_PARENT
。