앱 만들기/안드로이드

XML 과 커스텀 뷰 같이 사용하기

나도 처음이야 2022. 6. 21.

https://soo0100.tistory.com/1874

 

커스텀 뷰를 활용한 그리기

안드로이드 에선 기본적으로 XML로 화면을 구성하게 된다. XML 화면구성 -> 코드로 로직 구성 및 XML 컴포넌트들의 인 플레이트 어찌 보면 이 두 개가 다다. 물론 로직 구성을 위한 데이터 처리를 위

soo0100.tistory.com

 

이번 시간에는 XML 화면 구성에 자신이 만든 화면 (커스텀 뷰)를 넣어본다.

즉, 같이 사용한다는 것이고 여러가지 자율성이 높아진다.

1. MainActivity 는 고치지 않는다.

public class MainActivity extends AppCompatActivity {

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

2. 내가 만들 화면, 커스텀 뷰를 구성한다.

  - 이 커스텀 뷰를 XML에서 참조할 것 이다.

 - XML에서 참조(삽입) 하기 위해서는 하기 생성자가 필수 이다.

   MyView(Context context, AttributeSet attrs) 

   이건 규칙이니 그대로 따르자. XML에서 커스텀 뷰를 생성할때 AttributeSet 을 같이 넘겨서 객체를 만들기 때문일것이다.

public class MyView extends View {

    //View 의 생성자. 초기값으로 배경을 설정해주었다.
    public MyView(Context context){
        super(context);
        setBackgroundColor(Color.BLACK);
    }
    //XML에서 참조하기 위해서는 해당 생성자가 구현 필수!
    public MyView(Context context, AttributeSet attrs){
        super(context);
        setBackgroundColor(Color.BLACK);
    }
    // 화면으로 그려주는 곳이다...
    @Override
    protected void onDraw(Canvas canvas) {
        //페인트는 그림에서 붓과 물감등의 설정체라고 생각하자.
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);// 선의 색상
        paint.setStrokeWidth(20); // 선의 굵기
        paint.setAntiAlias(true);
        //해당 붓 으로 선을 그린다.
        canvas.drawLine(100,100,500,200,paint);
        canvas.drawRect(100,300,500,600, paint);
        paint.setColor(Color.YELLOW);// 선의 색상
        canvas.drawRoundRect(new RectF(550,50,800,500),30,30,paint);
        paint.setColor(Color.BLUE);// 선의 색상
        canvas.drawOval(new RectF(100,700,300,1000),paint);
        paint.setColor(Color.DKGRAY);// 선의 색상
        canvas.drawArc(new RectF(30,170,150,300), 0,300,true,paint);
        canvas.drawCircle(700,800,200,paint);
        paint.setTextSize(80);
        canvas.drawText("Zorro",100,1200,paint);
        paint.setStrokeWidth(10);
        canvas.drawLines(new float[]{100,1250,800,1250,800,1250,30,1450,40,1450,850,1450}, paint);
    }
}

3. activity_main.xml 화면 구성을 수정한다.

-  화면에 위치할 곳에 커스텀 뷰 패키지 명이 붙은 클래스명을 적어준다.

   이 코드가 바로 XML에서 커스텀 뷰를 참조(삽입) 하는 방식이다.

<bluemooninsea.soo.graphic.MyView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="8" />
<?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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <bluemooninsea.soo.graphic.MyView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="8" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:text="Button" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

LinearLayout 을 사용하였고, 컴포넌트 뷰의 적절한 배치를 위해서 layout_weight 를 사용해서 가중치를 주었다.

결과 화면은, 위에는 내가 만든 커스텀 뷰가

밑에는 XML 에서 지원해주는 버튼 뷰 컴포넌트가 들어갔다.

여러 화면을 구성시 응용할 수 있다. 

 

layout_weight 의 사용법에 대해서는

하기 포스팅을 참고드립니다. 감사합니다.

https://soo0100.tistory.com/1582

 

안드로이드 layout_weight 사용법 그리고 주의할 점

LinearLayout 을 사용할 때, 자식 오브젝트들에 layout_weight 설정을 할 수 있다. layout_weight의 크기에 따라서 폭, 길이 등을 손쉽게 제어가 가능하기 때문이다. 하지만, layout_weight 사용시 주의점이 있다

soo0100.tistory.com

 

반응형

댓글