我想在相对布局(Container
)的中心膨胀一个可移动的按钮,这样当触摸它时,它可以在 内移动Container
,即屏幕。
代码如下:
public void inflate_floating_btn(int k)
{
floatButton = new Button(this);
floatButton.setId(k);
floatButton.setTag(k);
final int id_ = floatButton.getId();
floatButton.setEnabled(true);
floatButton.setText("hello");
floatButton.setTextColor(Color.BLACK);
floatButton.setBackgroundResource(R.drawable.transparent_btn);
RelativeLayout.LayoutParams testLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
testLP.addRule(RelativeLayout.CENTER_IN_PARENT);
floatButton.setLayoutParams(testLP);
Container.addView(floatButton);
floatButton.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent e)
{
final int X = (int) e.getRawX();
final int Y = (int) e.getRawY();
switch(e.getAction() & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
layoutParams.leftMargin = Math.max((X - _xDelta), 0);
layoutParams.topMargin = Math.max((Y - _yDelta),0);
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
v.setLayoutParams(layoutParams);
break;
}
Container.invalidate();
return false;
}
});
}
按钮可以在屏幕中央充气。但是一碰就不能动。
如果更换
RelativeLayout.LayoutParams testLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
testLP.addRule(RelativeLayout.CENTER_IN_PARENT);
floatButton.setLayoutParams(testLP);
经过
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
该按钮现在可以在触摸时移动,但在相对布局的左上角膨胀。
问题:
如何改进代码以使移动按钮可以在屏幕中心充气并在触摸时移动?
谢谢!