Permalink
Browse files

Drag the Image Pieces Around

  • Loading branch information...
dragosholban committed Mar 8, 2018
1 parent 59e4425 commit cea16f68c9b443bd3eec65078cefb4a8037ddb41
@@ -8,6 +8,7 @@
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.ArrayList;
@@ -21,7 +22,7 @@ protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ConstraintLayout layout = findViewById(R.id.layout);
final RelativeLayout layout = findViewById(R.id.layout);
ImageView imageView = findViewById(R.id.imageView);
// run image related code after the view was laid out
@@ -30,9 +31,11 @@ protected void onCreate(Bundle savedInstanceState) {
@Override
public void run() {
pieces = splitImage();
TouchListener touchListener = new TouchListener();
for(Bitmap piece : pieces) {
ImageView iv = new ImageView(getApplicationContext());
iv.setImageBitmap(piece);
iv.setOnTouchListener(touchListener);
layout.addView(iv);
}
}
@@ -0,0 +1,30 @@
package dragosholban.com.androidpuzzlegame;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class TouchListener implements View.OnTouchListener {
private float xDelta;
private float yDelta;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getRawX();
float y = motionEvent.getRawY();
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
break;
case MotionEvent.ACTION_MOVE:
lParams.leftMargin = (int) (x - xDelta);
lParams.topMargin = (int) (y - yDelta);
view.setLayoutParams(lParams);
break;
}
return true;
}
}
@@ -4,8 +4,7 @@
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dragosholban.com.androidpuzzlegame.MainActivity"
android:id="@+id/layout">
tools:context="dragosholban.com.androidpuzzlegame.MainActivity">
<ImageView
android:id="@+id/imageView"
@@ -23,4 +22,14 @@
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/photo" />
<RelativeLayout
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</RelativeLayout>
</android.support.constraint.ConstraintLayout>

0 comments on commit cea16f6

Please sign in to comment.