I'm working on a app in which dynamic views are being generated onClick. The code is working fine but the problem is,when I drag the button to the previously generated buttons,it overlaps other button(s),which is not my requirement. What am I doing wrong? Or what is missing?
MainActivity.java
public class MainActivity extends Activity {
private Button btn;
private RelativeLayout rl1;
int i=0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl1=(RelativeLayout)findViewById(R.id.relative_layout);
btn=(Button)findViewById(R.id.btnAdd);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Button btn = new Button(MainActivity.this);
btn.setText(""+1+i);
i++;
RelativeLayout.LayoutParams rlparams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
rlparams.addRule(RelativeLayout.CENTER_IN_PARENT);
rlparams.leftMargin = 280;
btn.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
// when touching the img
case MotionEvent.ACTION_DOWN:
break;
// when moving
case MotionEvent.ACTION_MOVE:
btn.setX(btn.getX()+ event.getX()- btn.getWidth() / 2);
btn.setY(btn.getY()+ event.getY()- btn.getHeight() / 2);
break;
// when not touched
case MotionEvent.ACTION_UP:
if ((btn.getY() < rl1.getY())) {
btn.setY(event.getRawY());
} else if (btn.getX() < rl1.getX()) {
// btn.setY(event.getRawY());
btn.setX(event.getRawX());
} else if (btn.getX()+btn.getWidth()>rl1.getX()+rl1.getWidth()) {
btn.setX(event.getRawY());
}
break;
default:
break;
}
return true;
}
});
rl1.addView(btn);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="AddButton"
android:text="Button" />
</RelativeLayout>
0 comments:
Post a Comment