Android Move Text With Arrow Key Example

When you play a game, you will find the arrow key is a good control method to move the view object on your screen. This example will show you how to use the keyboard arrow key to move the text view on the android screen. It also demonstrates how to make the text move follow your finger touch by implement custom View‘s onTouchListener method.

1. Move Text View By Keyboard Arrow Key Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/69-q_f_Ipvg

  1. In the above android emulator, when you press the machine keyboard arrow key, the text will move follow the key.

2. Move Text By KeyBoard Example Source Code.

  1. Below is the example project files list.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\ANDROIDEXAMPLEPROJECT\MOVEIMAGEWITHKEY
    │   .gitignore
    │   build.gradle
    │   gradle.properties
    │   gradlew
    │   gradlew.bat
    │   settings.gradle
    │
    ├───.idea
    │       gradle.xml
    │       misc.xml
    │       modules.xml
    │       runConfigurations.xml
    │
    ├───app
    │   │   .gitignore
    │   │   build.gradle
    │   │   proguard-rules.pro
    │   │
    │   └───src
    │       ├───androidTest
    │       │   └───java
    │       │       └───com
    │       │           └───dev2qa
    │       │               └───moveimagewithkey
    │       │                       ExampleInstrumentedTest.java
    │       │
    │       ├───main
    │       │   │   AndroidManifest.xml
    │       │   │
    │       │   ├───java
    │       │   │   └───com
    │       │   │       └───dev2qa
    │       │   │           └───moveimagewithkey
    │       │   │                   CustomView.java
    │       │   │                   MainActivity.java
    │       │   │
    │       │   └───res
    │       │       ├───drawable
    │       │       │       ic_launcher_background.xml
    │       │       │
    │       │       ├───drawable-v24
    │       │       │       ic_launcher_foreground.xml
    │       │       │
    │       │       ├───layout
    │       │       │       activity_main.xml
    │       │       │
    │       │       ├───mipmap-anydpi-v26
    │       │       │       ic_launcher.xml
    │       │       │       ic_launcher_round.xml
    │       │       │
    │       │       ├───mipmap-hdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-mdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       ├───mipmap-xxxhdpi
    │       │       │       ic_launcher.png
    │       │       │       ic_launcher_round.png
    │       │       │
    │       │       └───values
    │       │               colors.xml
    │       │               strings.xml
    │       │               styles.xml
    │       │
    │       └───test
    │           └───java
    │               └───com
    │                   └───dev2qa
    │                       └───moveimagewithkey
    │                               ExampleUnitTest.java
    │
    └───gradle
        └───wrapper
                gradle-wrapper.jar
                gradle-wrapper.properties
  2. You should create a custom view that extends the android.view.View class.
  3. All the text move action is processed in the custom class. Because of this, it does not need a layout XML file.

2.1 Main Activity Java File.

  1. MainActivity.java
    package com.dev2qa.moveimagewithkey;
    
    import android.content.Context;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.Window;
    import android.view.WindowManager;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // Must comment below code.
            //setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Move Text By Arrow Key Example.");
    
            // Hide app action bar.
            getSupportActionBar().hide();
            //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    
            // Make app full screen.
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    
            Context context = getApplicationContext();
    
            int x = 10;
    
            int y = 100;
    
            // Create a new custom view object.
            final CustomView customView = new CustomView(context, x, y, "Hello Dev2qa.com");
    
            // Set a onTouchListener to response to user finger touch event.
            customView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
    
                    // Get current user finger touch x and y coordinates.
                    float touchX = motionEvent.getX();
                    float touchY = motionEvent.getY();
    
                    // Set finger touch x and y value to custom view.
                    customView.setTextX(touchX);
                    customView.setTextY(touchY);
    
                    // Invoke custom view's onDraw method.
                    customView.invalidate();
    
                    // Return true to tell android os onTouch event has been processed.
                    return true;
                }
            });
    
            // Apply the custom view object to current activity.
            setContentView(customView);
        }
    }

2.2 Custom View Java Class.

  1. CustomView.java
    package com.dev2qa.moveimagewithkey;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.view.KeyEvent;
    import android.view.View;
    
    public class CustomView extends View {
    
        // Text x coordinate.
        private float textX = 0;
    
        // Text y coordinate.
        private float textY = 0;
    
        // Text move step when click arrow key.
        private int moveStep = 25;
    
        // Move text.
        private String moveText = "";
    
        public CustomView(Context context,int x,int y, String text) {
            super(context);
    
            textX = x;
    
            textY = y;
    
            moveText = text;
    
            // Make this view focusable.
            setFocusable(true);
    
            setBackgroundColor(Color.BLUE);
        }
    
        /* Invoked when the view is first created or invalidated.*/
        @Override
        protected void onDraw(Canvas canvas) {
    
            // Create a Paint object.
            Paint paint = new Paint();
    
            // Set paint color and text size.
            paint.setColor(Color.GREEN);
            paint.setTextSize(100);
    
            // Draw text on the canvas with the paint.
            canvas.drawText(this.moveText, textX, textY, paint);
    
            super.onDraw(canvas);
        }
    
        /* Response to key down event. */
        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
    
            switch (keyCode){
    
                case KeyEvent.KEYCODE_DPAD_UP:
                    textY -= moveStep;
                    break;
    
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    textY += moveStep;
                    break;
    
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    textX -= moveStep;
                    break;
    
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    textX += moveStep;
                    break;
            }
    
            // Tell the view to redraw the canvas then the onDraw method will be invoked.
            invalidate();
    
            return super.onKeyDown(keyCode, event);
        }
    
        public float getTextX() {
            return textX;
        }
    
        public void setTextX(float textX) {
            this.textX = textX;
        }
    
        public float getTextY() {
            return textY;
        }
    
        public void setTextY(float textY) {
            this.textY = textY;
        }
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Sadasiva Pallai
Sadasiva Pallai

thnx!!! but i want to ask that if we want to move an image instead of text. then what should be the code???

1
0
Would love your thoughts, please comment.x
()
x