Canvas draw path in android - java

I am a new beginner in android and I want to make a simple program that detect touch coordinates and draw a circle and path of touch, I make a simple program that draw a circle around the touch and follow it but I still can do the path of touch. When I start the program with path it crash, when I remove the path it works normal...
public class MainActivity extends Activity {
float x = 0;
float y = 0;
LinearLayout layout; //declarea variabilor pentru desenarea cercului
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //specificarea
layout = (LinearLayout)findViewById(R.id.layout); //gasirea id
layout.addView(new CustomView(MainActivity.this));
}
public class CustomView extends View { //crearea unei mape pentru canvas
Bitmap mBitmap;
Paint paint;
Path path;
public CustomView(Context context) {
super(context);
mBitmap = Bitmap.createBitmap(640, 1024, Bitmap.Config.ARGB_8888);
paint = new Paint();
path = new Path();
paint.setColor(Color.BLUE);//culoare cercului desenat
paint.setStyle(Style.FILL);
}
protected void onDraw(Canvas canvas) {//desenarea cercului la atingere
super.onDraw(canvas);
canvas.drawPath(path,paint);
canvas.drawCircle(x, y, 25, paint);
}
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(), event.getY());
path.lineTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
x = event.getX();
y = event.getY();
path.lineTo(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
path.lineTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

You are not initializing path. Most likely, your program is crashing with a NullPointerException. Try adding this inside the CustomView constructor:
path = new Path();
In the future, when you are posting about your Android program crashing, it would be most helpful if you posted the logcat output from a crash.

Related

How to paint on Bitmap using canvas drawPath or Path? I tried several tutorials but failed

So this is my current code which uses canvas drawLine, where I'm trying to modify it into drawPath.
My Declared Variables in Main Activity :
ImageView imageResult;
final int RQS_IMAGE1 = 1;
Paint paint;
Uri source;
Bitmap bitmap;
Canvas canvas;
Path path;
My code in On Create method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_board);
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setStrokeWidth(10);
//result is the ID of imageview
imageResult = findViewById(R.id.result);
//The user will select Images on gallery
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_IMAGE1);
Where selected image pass into imageResult variable and then converted into bitmap, and that bitmap will be place into the canvas :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap tempBitmap;
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RQS_IMAGE1:
source = data.getData();
try {
//tempBitmap is Immutable bitmap,
//cannot be passed to Canvas constructor
tempBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source));
Bitmap.Config config;
if (tempBitmap.getConfig() != null) {
config = tempBitmap.getConfig();
} else {
config = Bitmap.Config.ARGB_8888;
}
//bitmap is Mutable bitmap
bitmap = Bitmap.createBitmap(
tempBitmap.getWidth(),
tempBitmap.getHeight(),
config);
canvas = new Canvas(bitmap);
canvas.drawBitmap(tempBitmap, 0, 0, null);
imageResult.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
Now, this is the method where I get the touch points of users finger and put the canvas.drawLine inside of motion events. So then, they can paint on the canvas where the Imageview is placed :
private float mX,mY;
public void paintOn_Image(){
imageResult.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mX = x;
mY = y;
float ratioWidth = (float)bitmap.getWidth()/(float)v.getWidth();
float ratioHeight = (float)bitmap.getHeight()/(float)v.getHeight();
canvas.drawLine(
mX * ratioWidth,
mY * ratioHeight,
x * ratioWidth,
y * ratioHeight,
paint);
imageResult.invalidate();
break;
case MotionEvent.ACTION_MOVE:
ratioWidth = (float) bitmap.getWidth() / (float) v.getWidth();
ratioHeight = (float)bitmap.getHeight()/(float)v.getHeight();
canvasMaster.drawLine(
mX * ratioWidth,
mY * ratioHeight,
x * ratioWidth,
y * ratioHeight,
paint);
imageResult.invalidate();
mX = x;
mY = y;
break;
case MotionEvent.ACTION_UP:
ratioWidth = (float) bitmapMaster.getWidth() / (float) v.getWidth();
ratioHeight = (float)bitmapMaster.getHeight()/(float)v.getHeight();
canvasMaster.drawLine(
x * ratioWidth,
y * ratioHeight,
x * ratioWidth,
y * ratioHeight,
paint);
imageResult.invalidate();
break;
}
return true;
}
});
Here's what I've done so far.
In the motionEvent.ACTION_DOWN,ACTION_MOVE & ACTION_UP, I change this :
canvas.drawLine(
mX * ratioWidth,
mY * ratioHeight,
x * ratioWidth,
y * ratioHeight,
paint);
imageResult.invalidate();
break;
Into this :
path.moveTo(mX*ratioWidth,mY*ratioHeight);
path.lineTo(x*ratioWidth,y*ratioHeight);
path.moveTo(mX*ratioWidth,y*ratioHeight);
path.lineTo(x*ratioWidth,mY*ratioHeight);
canvas.drawPath(path,paintDraw);
imageResult.invalidate();
canvas.drawPath(path, paint);
imageResult.invalidate();
break;
But the application is crashing when the user touch the canvas :(
How can I paint on canvas using Path? Is the calculation incorrect?
The reason why I'm trying to change it into path is we can't undo the
drawLine after painting into the canvas. So if you have solution to
undo/clear/remove the drawLine, that will also work for me. Thank you.
After reading a lot of documentation and tutorials and informations in this forum.
Just Create DrawableView and CustomImageview instead of dwelling on Imageview.
Sources

ClassCastException with no debuggable errors

I am trying to create an object of fingerline(class) in drawline(activity).The fingerline takes the context of MainActivity(activity).I get ClassCastException showing that
Process: com.example.caddrawingtool, PID: 11405
java.lang.RuntimeException: Unable to instantiate application
com.example.caddrawingtool.MainActivity: java.lang.ClassCastException:
com.example.caddrawingtool.MainActivity cannot be cast to android.app.Application
at android.app.LoadedApk.makeApplication(LoadedApk.java:1226)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6504)
at android.app.ActivityThread.access$1400(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1892)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7436)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
I have changed getApplicationContext() in drawline where the fingerline object was created to Activity context by using
this
I am not able to use
MainActivity.this
though.
Is there a way to simplify all this?
My MainActivity code:
public class MainActivity extends AppCompatActivity {
fingerline dv;
private Paint mpaint;
private Context context;
MainActivity MainActivity(){
return MainActivity.this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dv = new fingerline(this);
setContentView(dv);
dv.setBackgroundColor(Color.BLACK);
mpaint = new Paint();
mpaint.setAntiAlias(true);
mpaint.setDither(true);
mpaint.setColor(Color.WHITE);
mpaint.setStyle(Paint.Style.STROKE);
mpaint.setStrokeJoin(Paint.Join.MITER);
mpaint.setStrokeCap(Paint.Cap.ROUND);
mpaint.setStrokeWidth(12);
getSupportActionBar().setTitle("3D TOOL");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.line:
Intent intent = new Intent(this, drawline2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
break;
case R.id.circle:
Intent intent1=new Intent(this,drawcircle.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent1);
break;
case R.id.rectangle:
Intent intent2=new Intent(this,drawrectangle.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent2);
break;
case R.id.offset:
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
My fingerline code:
public class fingerline extends View {
public int width, height;
private Bitmap mbitmap;
private Canvas mcanvas;
private Paint mpaint, mbitmappaint, circlepaint;
private float startx;
private float starty;
private float endx;
private float endy;
private Path path, circlepath;
Context c;
public fingerline(Context context) {
super(context);
// c = context;
path = new Path();
mpaint = new Paint();
mbitmappaint = new Paint(Paint.DITHER_FLAG);
circlepaint = new Paint();
circlepath = new Path();
circlepaint.setAntiAlias(true);
circlepaint.setColor(Color.WHITE);
circlepaint.setStyle(Paint.Style.STROKE);
circlepaint.setStrokeJoin(Paint.Join.MITER);
circlepaint.setStrokeWidth(4f);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mbitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mcanvas = new Canvas(mbitmap);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mpaint.setStyle(Paint.Style.STROKE);
mpaint.setColor(Color.WHITE);
mpaint.setStrokeWidth(12);
mpaint.setAntiAlias(true);
mpaint.setDither(true);
mpaint.setStrokeJoin(Paint.Join.MITER);
mpaint.setStrokeCap(Paint.Cap.ROUND);
canvas.drawBitmap(mbitmap, 0, 0, mbitmappaint);
canvas.drawPath(path, mpaint);
canvas.drawPath(circlepath, circlepaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
path.reset();
path.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dX = Math.abs(x - mX);
float dY = Math.abs(y - mY);
if (dX >= TOUCH_TOLERANCE) {
path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
path.lineTo(mX, mY);
circlepath.reset();
mcanvas.drawPath(path, mpaint);
path.reset();
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startx = event.getX();
starty = event.getY();
touch_start(startx, starty);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
startx = event.getX();
starty = event.getY();
touch_move(startx, starty);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
My drawline code:
public class drawline2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawline2);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EditText editText, editText1;
editText = (EditText) findViewById(R.id.length);
editText1 = (EditText) findViewById(R.id.angle);
Canvas canvas;
Paint paint = new Paint();
Paint circlepaint = new Paint();
Path path = new Path();
Path cpath = new Path();
circlepaint.setAntiAlias(true);
circlepaint.setStrokeWidth(4f);
circlepaint.setColor(Color.WHITE);
circlepaint.setStyle(Paint.Style.STROKE);
circlepaint.setStrokeJoin(Paint.Join.MITER);
fingerline dv;
dv = new fingerline(this);
dv.setBackgroundColor(Color.BLACK);
setContentView(dv);
circlepaint.setAntiAlias(true);
circlepaint.setDither(true);
String value = editText.getText().toString();
int length =0;
double angle=0;
if(value!=null && value.length()>0){
try{
length = Integer.parseInt(value);
}
catch (NullPointerException e){
length=0;
}
}
String value1 = editText1.getText().toString();
if(value1!=null && value1.length()>0){
try{
angle = Double.parseDouble(value1);
}
catch (NullPointerException e){
angle=0;
}
}
int startX, startY, endX, endY, x, y;
x= 0;
y=0;
path.reset();
path.moveTo(x, y);
startX = (int) x;
startY = (int) y;
endY = (int) (x + length * Math.cos(angle));
endX = (int) (x + length * Math.sin(angle));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
Thanks in advance.
In short:
MainActivity cannot be cast to android.app.Application
You could make this an awful lot more readable by calling it DrawlineActivity and FingerlineActivity. Then just use this or DrawlineActivity.this as the Context.

How do you change the onTouchListener on the same animated image view?

Just like how those conveyors in some apps that you can swipe to the right to bring out (show it) and then swipe to the left to send back in, hiding it again. I tried using setOnTouchListener again on the same view with a delayed message after it's brought out, but the app receives an error and closes when you try to bring it out (show). If I am to remove the method that is supposed to make it go back in (hidden), it would be brought out just fine, but how do I make it happen that it could be sent back in and hidden through swiping to the left after it's been brought out by swiping to the right?
Here's the code I used in the activity:
ImageView conveyorWheel;
private float x1, x2;
static final int MIN_DISTANCE = 150;
RelativeLayout parentLayout;
android.os.Handler conveyorHandler;
conveyorWheel = (ImageView) findViewById(R.id.conveyerWheel);
parentLayout = (RelativeLayout) findViewById(R.id.parentLayout);
protected void onCreate(Bundle savedInstanceState) {
...
parentLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE & x1 < x2) {
conveyorWheel.animate()
.x(-750)
.setDuration(150)
.start();
conveyorHandler.postDelayed(new Runnable() {
#Override
public void run() {
conveyorRevert();
}
}, 151);
break;
}
default:
return false;
}
return true;
}
});
}
private void conveyorRevert (){
parentLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE){
conveyorWheel.animate()
.x(-950)
.setDuration(150)
.start();
break;
}
default: return false;
}
return true;
}
});
}
The Android Monitor displayed the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.postDelayed(java.lang.Runnable, long)' on a null object reference
But I have no idea how to fix this

Add custom view to xml layout

I have this signature view that enables you to basically draw on phones screen. Now I need to add this view as a background or use it like a widget on a xml layout but I have no idea how to do that. So please can anybody help me do this.
This is the signature view class that I have:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class SignatureView extends View {
private static final float STROKE_WIDTH = 5f;
/** Need to track this so the dirty region can accommodate the stroke. **/
private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
private Paint paint = new Paint();
private Path path = new Path();
/**
* Optimizes painting by invalidating the smallest possible area.
*/
private float lastTouchX;
private float lastTouchY;
private final RectF dirtyRect = new RectF();
public SignatureView(Context context, AttributeSet attrs, int background) {
super(context, attrs);
setBackgroundResource(background);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(STROKE_WIDTH);
}
public void setColor(int color){
paint.setColor(color);
}
/**
* Erases the signature.
*/
public void clear() {
path.reset();
// Repaints the entire view.
invalidate();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
// There is no end point yet, so don't waste cycles invalidating.
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
// Start tracking the dirty region.
resetDirtyRect(eventX, eventY);
// When the hardware tracks events faster than they are delivered, the
// event will contain a history of those skipped points.
int historySize = event.getHistorySize();
for (int i = 0; i < historySize; i++) {
float historicalX = event.getHistoricalX(i);
float historicalY = event.getHistoricalY(i);
expandDirtyRect(historicalX, historicalY);
path.lineTo(historicalX, historicalY);
}
// After replaying history, connect the line to the touch point.
path.lineTo(eventX, eventY);
break;
default:
// Log.("Ignored touch event: " + event.toString());
return false;
}
// Include half the stroke width to avoid clipping.
invalidate(
(int) (dirtyRect.left - HALF_STROKE_WIDTH),
(int) (dirtyRect.top - HALF_STROKE_WIDTH),
(int) (dirtyRect.right + HALF_STROKE_WIDTH),
(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));
lastTouchX = eventX;
lastTouchY = eventY;
return true;
}
/**
* Called when replaying history to ensure the dirty region includes all
* points.
*/
private void expandDirtyRect(float historicalX, float historicalY) {
if (historicalX < dirtyRect.left) {
dirtyRect.left = historicalX;
} else if (historicalX > dirtyRect.right) {
dirtyRect.right = historicalX;
}
if (historicalY < dirtyRect.top) {
dirtyRect.top = historicalY;
} else if (historicalY > dirtyRect.bottom) {
dirtyRect.bottom = historicalY;
}
}
/**
* Resets the dirty region when the motion event occurs.
*/
private void resetDirtyRect(float eventX, float eventY) {
// The lastTouchX and lastTouchY were set when the ACTION_DOWN
// motion event occurred.
dirtyRect.left = Math.min(lastTouchX, eventX);
dirtyRect.right = Math.max(lastTouchX, eventX);
dirtyRect.top = Math.min(lastTouchY, eventY);
dirtyRect.bottom = Math.max(lastTouchY, eventY);
}
}
and my main class:
public class Draw extends Activity {
DrawView drawView;
SignatureView signature;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full screen view
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
signature = new SignatureView(this, null,R.drawable.back);
setContentView(signature);
signature.requestFocus();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clear:
signature.clear();
return true;
case R.id.red:
signature.setColor(Color.RED);
return true;
case R.id.blue:
signature.setColor(Color.BLUE);
return true;
case R.id.yellow:
signature.setColor(Color.YELLOW);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
this.finish();
super.onBackPressed();
}
}
You'll reference this in your XML layouts by the full name, such as com.example.myapp.SignatureView.
<com.example.myapp.SignatureView android:id="#+id\my_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.example.myapp.SignatureView>
You can reference this in the code behind normally as well
SignatureView sv = (SignatureView)findViewById(R.id.my_id);
sv.setColor(Color.RED);
To add it to the xml, you add a tag like this <com.example.SignatureView /> where the com.example stuff is replaced by your package name. You can add parameters and sub-tabs as normal.

How to close OpenGL Activity

I have a problem with my activity which showing CUBE 3D (simple OpenGL example). When I pressing back key on my phone or emulator, it should return to main menu, but instead of returning nothing happens. Any clue?
Here's the code:
public class Graphic3D extends Activity {
private GLSurfaceView glView; // Use subclass of GLSurfaceView (NEW)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Allocate a custom subclass of GLSurfaceView (NEW)
glView = new MyGLSurfaceView(this);
setContentView(glView); // Set View (NEW)
}
#Override
public void onBackPressed() {
super.onBackPressed();
// ????????
}
#Override
protected void onPause() {
super.onPause();
glView.onPause();
}
#Override
protected void onResume() {
super.onResume();
glView.onResume();
}
}
MySurfaceView class:
public class MyGLSurfaceView extends GLSurfaceView {
Graphics3DRenderer renderer; // Custom GL Renderer
// For touch event
private final float TOUCH_SCALE_FACTOR = 180.0f / 320.0f;
private float previousX;
private float previousY;
// Constructor - Allocate and set the renderer
public MyGLSurfaceView(Context context) {
super(context);
renderer = new Graphics3DRenderer(context);
this.setRenderer(renderer);
// Request focus, otherwise key/button won't react
this.requestFocus();
this.setFocusableInTouchMode(true);
}
// Handler for key event
#Override
public boolean onKeyDown(int keyCode, KeyEvent evt) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: // Decrease Y-rotational speed
renderer.speedY -= 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase Y-rotational speed
renderer.speedY += 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_UP: // Decrease X-rotational speed
renderer.speedX -= 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: // Increase X-rotational speed
renderer.speedX += 0.3f;
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:// Zoom out (decrease z)
renderer.z -= 0.4f;
break;
case KeyEvent.KEYCODE_VOLUME_UP: // Zoom in (increase z)
renderer.z += 0.4f;
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
renderer.speedY = 0;
renderer.speedX = 0;
renderer.z = -6.0f;
break;
}
return true; // Event handled
}
// Handler for touch event
#Override
public boolean onTouchEvent(final MotionEvent evt) {
float currentX = evt.getX();
float currentY = evt.getY();
float deltaX, deltaY;
switch (evt.getAction()) {
case MotionEvent.ACTION_MOVE:
// Modify rotational angles according to movement
deltaX = currentX - previousX;
deltaY = currentY - previousY;
renderer.angleX += deltaY * TOUCH_SCALE_FACTOR;
renderer.angleY += deltaX * TOUCH_SCALE_FACTOR;
}
// Save current x, y
previousX = currentX;
previousY = currentY;
return true; // Event handled
}
}
In an Activity, calling finish() will close the current Activity. If you haven't closed the main menu Activity, it should "open" itself.
If you need to start an Activity again, for example if your menu Activity is closed, you can do the following.
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
finish();

Categories