Android Move Text With Arrow Key Example

When you play game, you will find the arrow key is a good control method to move the view object in your screen. This example will show you how to use keyboard arrow key to move text view in android screen. It also demonstrate 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.

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

2. Move Text By KeyBoard Example Source Code.

move text by keyboard example source code

You should create a custom view which extends android.view.View class. All the text move action is processed in the custom class. Because of this, it do not need a layout xml file.

2.1 Main Activity Java File.

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.

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;

/**
 * Created by zhaosong on 2018/6/15.
 */

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;
    }
}
READ :   How To Play Gif File Use Android.Graphics.Movie Class

Leave a Reply

Your email address will not be published. Required fields are marked *

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