我正在使用引用https://github.com/ApmeM/android-flowlayout的流布局。现在我在这个布局上创建多个动态按钮并在它们上设置ontouchlistener。问题是当我通过触摸改变一个按钮的位置时,其他按钮也正在改变那里的位置。我想改变我所触摸的唯一按钮的位置。有没有办法做到这一点或其他解决方案。
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
Button floatButton;
Button _view;
private int _xDelta;
private int _yDelta;
ViewGroup layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
layout = (ViewGroup) findViewById(R.id.flowLayout);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = 50;
layoutParams.topMargin = 50;
layoutParams.bottomMargin = 0;
layoutParams.rightMargin = 0;
for (int i = 0; i < 10; i++) {
_view = new Button(this);
_view.setText("Button"+(i+1));
_view.setLayoutParams(layoutParams);
_view.setOnTouchListener(this);
layout.addView(_view);
}
}
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
try {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
FlowLayout.LayoutParams lParams = (FlowLayout.LayoutParams) view.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:
FlowLayout.LayoutParams layoutParams = (FlowLayout.LayoutParams) view.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
}catch (Exception ex){
Log.d("ON Touch ", ex.toString());
}
layout.invalidate();
return true;
}
}
答案 0 :(得分:0)
这种情况发生的可能性很大,因为您正在使用RelativeLayout,并且其他对象位置以某种方式相对于您正在移动的按钮进行了定义。如果是这种情况,那么您所描述的行为是预期的。但我们需要查看XML文件以确切知道发生了什么。