Published Date : 2021年2月2日12:43

3. 賃金階級年齢階級別労働者割合のアンドロイドアプリ
3. Android application for ratio of workers by wage class and age group


This blog has an English translation


ニコニコ動画にアップした動画のまとめ記事です。

This is a summary blog post about a video I uploaded to NicoNico.

細かい部分は動画を参考にしてください。

Please refer to the video for details.


目次

Table of Contents




① 動画の説明
① Video Description



前回の続きです。

Continued from last time.

Viewクラスを拡張して、独自の棒グラフ用のViewクラスのサブクラスDisplayViewを作成しましょう。

Let's extend the View class to create a subclass of the View class, DisplayView, for our own bar chart.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.view.View;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class DisplayView extends View {

テキストや図形の色等の情報を保持するPaintクラスの変数を宣言します。

Declare variables of the Paint class that hold information such as the color of text and geometry.

Paint paint;
Paint selectPaint;
Paint strokePaint;
Paint linePaint;
Paint textPaint;
Paint wageTextPaint;
Paint percentagePaint;
Paint selectWagePaint;
Paint averagePaint;
Paint averageTextPaint;
Paint averageTextPaintMedium;
Paint averageTextPaintSmall;

グラフの外枠の場合は線だけを表示する、テキストやグラフの場合は塗りつぶす等、図形やテキスト毎にスタイルを決めていく為、複数のPaint型の変数を用意します。

Multiple variables of type Paint are prepared to determine the style for each shape or text, such as displaying only lines in the case of the outer frame of the chart, or filling in the case of text or chart.

float strokeWidth;
float lineWidth;
float textStrokeWidth;
float textSize;
float wageTextWidth;
float wageTextSize;
float averageTextWidth;
float averageTextSize;

int blackColor;
int redColor;
int pinkColor;
int purpleColor;
int blueColor;

float w;
float h;
float outLineW;
float outLineH;

float gridW;
float gridH;

float outLineWoffset;
float outLineHoffsetTop;
float outLineHoffsetBttom;
float rowSize;
float colSize;
float gridWspacing;

String percentage;
String wage;
String age;
List<String> ageSpecific;
int wageIndex;
List<String> wageClassList;
float wageAvarage;
List<List<String>> replacedWageClassList;

int averageIdx;

コンストラクタを作成し、実際に棒グラフの表示をするonDrawメソッドをオーバーライドします。

Create a constructor and override the onDraw method to actually display the bar chart.

public DisplayView(Context context, List<Object> receivedData) {
    super(context);
    DisplayMetrics metrics = context.getApplicationContext().getResources().getDisplayMetrics();

onDrawメソッドには棒グラフの線やテキストや図形等を描画する為に必要なCanvasオブジェクトをパラメータとして渡します。

The onDraw method takes as a parameter a Canvas object which is needed to draw bar lines, text, graphics, etc.

Processingを使ったことのある人なら直観的に理解できるかもしれません。

If you've ever used Processing, you may be able to understand it intuitively.

コンストラクタはProcessingのsetup関数に似ていて、onDrawはProcessingのDraw関数に似ています。

The constructor is similar to the setup function in Processing, and onDraw is similar to the Draw function in Processing.

因みに、Canvasクラスを使ってProcessingのようなアニメーションを実現するにはAnimationクラスとapplyTransformationメソッドを使用します。

Incidentally, the Animation class and applyTransformation method are used to implement Processing-like animation using the Canvas class.

そのメソッドに引数として渡されるinterpolatedTimeがProcessingで言うところのFrameRateに相当します。

The interpolatedTime passed as an argument to the method is equivalent to the FrameRate in Processing.

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;


public class MainActivity extends AppCompatActivity {

    private int ypos = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DisplayView displayView = new DisplayView(this);
        setContentView(displayView);

        int yPosToEnd = 750;
        MyAnimation myAnimation = new MyAnimation(displayView, yPosToEnd);
        myAnimation.setDuration(3000);
        displayView.startAnimation(myAnimation);
    }

    public class DisplayView extends View {

        Paint paint;
        float w;

        public DisplayView(Context context) {
            super(context);
            DisplayMetrics metrics = context.getApplicationContext().getResources().getDisplayMetrics();
            w = metrics.widthPixels;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            paint = new Paint();
            paint.setColor(Color.argb(222, 255, 0, 0));
            canvas.drawCircle(w/2, 30 + ypos, 120.0f, paint);
        }

        public int getYPosition() {
            return ypos;
        }

        public void setYPositon(int currentYPos) {
            ypos = currentYPos;
        }
    }

    public class MyAnimation extends Animation {

        private int previousYPos = 0;
        private int yPosToEnd = 0;

        private DisplayView displayView;

        MyAnimation(DisplayView displayView, int ypos) {
            previousYPos = displayView.getYPosition();
            yPosToEnd = ypos;
            this.displayView = displayView;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation transformation) {
            int nextYPos = (int)((yPosToEnd-previousYPos)*interpolatedTime);

            displayView.setYPositon(nextYPos);
            displayView.requestLayout();
        }

    }

}

今回はアニメーション機能は使いませんが、Processingに慣れている人なら棒グラフの作成は簡単に行えるはずです。

We won't use the animation feature this time, but if you're familiar with Processing, you can easily create a bar chart.

DisplayViewのコンストラクタにコンテキストのオブジェクトをパラメータとして渡し、親クラスのコンストラクタに渡します。

You pass the object of the context as a parameter to the DisplayView constructor and pass it to the constructor of the parent class.

このコンテキストとは、簡単に言ってしまえば、アプリ全体の環境情報等をAndroidのOS間で受け渡しをできるようにするためのインターフェイスの役割のようなものです。

To put it simply, this context is like the role of an interface that allows the environment information of the whole application to be transferred between Android OS.

そして、アンドロイド端末のディスプレイ情報(画面の幅等)を取得するために、DisplayMetricsのオブジェクトを作成しましょう。

Create a DisplayMetrics object to retrieve the display information (Screen width, etc.) of your Android device.

図形やテキストの線の幅を細かく指定する為の変数を宣言します。

Declare variables to specify the line width of shapes and text.

図形やテキストの色を指定する為の変数を宣言します。

Declare variables that specify the color of shapes and text.

画面の幅や高さ、棒グラフ一つ一つの幅を均一にする、間隔を決める等の変数を宣言します。

Declare variables that specify the width and height of the screen, the width of each bar, the interval between bars, etc.

メインアクティビティから渡された、年齢や図形に必要な高さの情報等を受け取る変数を宣言します。

Declare variables that will receive information from the main activity, such as age and shape height.

宣言した変数をコンストラクタ内で初期化していきます。

Initialize the variables declared in the constructor.

色や線の幅等は各自で好きなように調整してください。

Adjust the color and line width as you like.

グラフの目盛り用に表示される賃金階級の割合等のテキスト情報を見やすくする為の処理です。

These are the processes to make the text information such as the ratio of the wage class displayed for the scale of the chart easy to read.

ではonDrawメソッド内の処理を書いていきます。

Now you will write the process in the onDraw method.

まずはコンストラクタ内で初期化したPaintオブジェクト変数に色や線の幅、どのように図形を塗りつぶすかの情報を設定していきます。

First, you set the color, line width, and how you want to fill the shape in the Paint object variable that you initialized in the constructor.

setStyleメソッド内で使われているSTROKEは線のみを描画、FILL_AND_STROKEは線も含めて指定された座標内を指定された色で塗りつぶすことを意味しています。

STROKE, used in the setStyle method, only draws lines, while FILL_AND_STROKE means to fill the specified coordinates, including lines, with the specified color.

drawRectメソッドには左上のxとyの座標と右下のxとyの座標の四つの数値と、Paintオブジェクトを渡すことで、長方形を画面に描くことができます。

You can draw a rectangle on the screen by passing four numbers to the drawRect method, the upper left x and y coordinates, the lower right x and y coordinates, and a Paint object.

drawTextメソッドには表示したいテキストと、テキストのxとyの座標とPaintオブジェクトを渡してやれば、テキストを画面に表示できます。

You can use drawText to display text on the screen by passing the text you want to display, the x and y coordinates of the text, and a Paint object.

もちろん、テキストのxとyの座標をセンター寄りにするか等の細かい指定もできます。

Of course, you can also specify details such as whether the x and y coordinates of the text should be centered.

例えば中央寄せにしたい場合は[yourPaintObject.setTextAlign(Paint.Align.CENTER);]等と書きます。

For example, if you want it to be centered, write [yourPaintObject.setTextAlign(Paint.Align.CENTER);].

後はForループを使用して、棒グラフの数を指定してそれぞれのインデックスに対しての処理を指定して、グラフの描画を行うだけです。

All that remains is to draw the chart using the For loop, specifying the number of bars and the action for each index.

色々と細かく変数が指定されていますが、単純な算数を使っているだけなので、各自で工夫しながら実装できると思います。

Many variables are specified in detail, but I think you can implement it by yourself as you only use simple arithmetic.

最後にグラフの目盛りの線を描画します。

Finally, draw tick marks for the chart.

ではアプリを動かして、その挙動を確かめてみてください。

Now, run the app and see how it works.

各自で色々と試して、もっと良いアプリに仕上げてください。

Please try various things on your own and make it a better application.



以上です。お疲れ様です。

That's all. Thank you for your hard work.