I am using flow layout from reference https://github.com/ApmeM/android-flowlayout .Now i am creating multiple dynamic buttons on this layout and setting ontouchlistener on them.The problem is that when i am changing the position of one button by touching, other buttons are also changing there position.I want to change the position of only button that i am touching.Is there any way to do that or other solution.
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;
}
}
More than likely this is happening because you are using a RelativeLayout and the other object positions are somehow defined relative to the button you are moving. If this is the case, then the behavior you describe is expected. But we need to see the XML file to know exactly what is going on.