버튼을 누르면 화면에 원이 그려지는 앱 - Random클래스 사용

Dora·2020년 11월 5일
0

Chap6. 인터페이스 기초03 - Custom View, Toast, Beep, Vibration, etc
패키지명 : CustomViewTest

  • 해야할 것
  1. 초기상태에는 빈화면, 버튼을 누르면 원이 그려짐
  2. Random 클래스를 사용할 것
  3. CustomView를 XML 레이아웃에 배치할 것

1. 초기상태에는 빈화면, 버튼을 누르면 원이 그려짐

버튼을 누르면 x좌표 100, y좌표 100, 반지름 80의 cyan색상의 원이 표시됨.

//MainActivity
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyView myView = findViewById(R.id.myView);
}

public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                myView.setCircleX(100);
                myView.setCircleY(100);
                myView.setCircleR(80);
                myView.invalidate();
                break;
        }
}

//myView
public class MyView extends View {

    int x, y ,r;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setCircleX(int x) { this.x = x; }

    public void setCircleY(int y) { this.y = y; }

    public int getCircleX() { return x; }

    public int getCircleY() { return y; }

    public void setCircleR(int r) { this.r = r; }

    public int getCircleR() { return r; }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.YELLOW);

        Paint pnt = new Paint();
        pnt.setColor(Color.CYAN);

        canvas.drawCircle(getCircleX(), getCircleY(), getCircleR(), pnt);
    }
}
  • 실행 결과


2. Random 클래스를 사용할 것

x, y, r값을 random 지정

  • Random 클래스
Random random = new Random();

//정수 범위 0~500, 0~800
int x = random.nextInt(500);
int y = random.nettInt(800);

//정수 범위 0~3
int r = (random.nextInt(3)+1) * 100;
//MainActivity
@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        int width = myView.getWidth();
        int height = myView.getHeight();
    }

    public void onClick(View v) {
    	Random random = new Random();
        switch (v.getId()) {
            case R.id.button:
                myView.setCircleX(random.nextInt(width));
                myView.setCircleY(random.nextInt(height));
                myView.setCircleR((random.nextInt(3) + 1) * 100);
                myView.invalidate();
                break;
        }
    }

//random.nextInt(view의 사이즈)이므로 myView의 width와 height를 구해 상수화하여 대입하였다.

  • 실행 결과


3. CustomView를 XML 레이아웃에 배치할 것

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    ...

    <ddwucom.mobile.test05.MyView
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>

전체코드

  • MainActivity.java
package ddwucom.mobile.test05;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    Random random = new Random();
    private MyView myView;
    int width, height;

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

        myView = findViewById(R.id.myView);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        width = myView.getWidth();
        height = myView.getHeight();
    }

    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.button:
                myView.setCircleX(random.nextInt(width));
                myView.setCircleY(random.nextInt(height));
                myView.setCircleR((random.nextInt(3) + 1) * 100);
                myView.invalidate();
                break;
        }
    }
}
  • MyView.java
package ddwucom.mobile.test05;

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

import androidx.annotation.Nullable;

import java.util.Random;

public class MyView extends View {

    int x, y ,r;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setCircleX(int x) { this.x = x; }

    public void setCircleY(int y) { this.y = y; }

    public int getCircleX() { return x; }

    public int getCircleY() { return y; }

    public void setCircleR(int r) { this.r = r; }

    public int getCircleR() { return r; }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.YELLOW);

        Paint pnt = new Paint();
        pnt.setColor(Color.CYAN);

        canvas.drawCircle(getCircleX(), getCircleY(), getCircleR(), pnt);
    }
}
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:onClick="onClick"
        android:text="@string/btn_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ddwucom.mobile.test05.MyView
        android:id="@+id/myView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • strings.xml
<resources>
    <string name="app_name">CustomViewTest</string>
    <string name="btn_name">CIRCLE DRAW</string>
</resources>
profile
Lv.1 개발자

0개의 댓글