0
我使用的是从参考https://github.com/ApmeM/android-flowlayout的流布局。现在我在这个布局上创建多个动态按钮并在它们上设置ontouchlistener。问题是,当我更改一个按钮的位置通过触摸,其他按钮也正在改变那里的位置。我想改变我只触摸按钮的位置。有没有办法做到这一点或其他解决方案。使用流布局在多个动态按钮上设置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;
}
}
是否有任何其他的解决方案,我只是想添加动态按钮到屏幕上,并希望他们在触摸监听器上实现。 –
您仍然可以使用相对布局,但您必须将项目相对于父项定位,而不是彼此定位。或者,如果只有几个按钮需要移动,则可以尝试将它们与框架布局分层。 –
谢谢bremen_matt。你可以请解释如何定位相对于父项的项目,如果我从xml布局文件充气按钮。 –