본문 바로가기
Android/Android Basic

안드로이드 레이팅바(RatingBar) 기본

by 수쓰뎁 2023. 1. 15.


1. RatingBar

레이팅바는 시크바와 프로그레스바의 확장판이다.

레이팅바는 별점을 표시하고 싶을 때 사용한다.

주로 평점주기 같은 기능에 활용된다.

별들의 개수는 자바코드에서는 setNumStars(int)로 설정하고 xml파일에서는 numStars 속성을 이용하여 표시한다.

xml 파일에서 레이아웃 설정 시, 레이아웃의 너비가 wrap_content로 되어 있어야 올바르게 보여진다.


2. 레이팅바 구현

안드로이드 레이팅바 예제를 만들어보자.

레이팅바 예제 테스트를 위해 다음과 같은 순서로 코드를 작성한다.

  • drawable 디렉터리에 이미지파일 저장
  • activity_main.xml 작성
  • MainActivity.java 작성

구현하고자 하는 것은 다음과 같다.

  • 작품에 대해 평점을 입력하는 앱을 구현한다.
  • 레이팅바의 별점을 선택한 후 Submit 버튼을 누르면 하단에 점수가 표시된다.

 

1) image 파일 저장

내가 임의로 만든 이미지 파일 작품을 연결해본다.

연결할 이미지를 프로젝트 디렉터리 창의 res - drawable에 복사한다.

이전의 체크박스 때와 같은 이미지파일을 사용한다.

이미지로 사용할 png 파일을 res - drawable 디렉터리로 이동하였다.

 

2) activity_main.xml

다음 작업으로 레이아웃을 구성해보자.

리니어 레이아웃을 기본으로하여 레이아웃을 작성한다.

레이아웃에 사용하는 위젯으로 <ImageView>, <RatingBar>, <Button>을 사용한다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:context=".MainActivity">

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

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            android:gravity="center"
            android:text="작품을 평가해주세요."
            android:textColor="@color/black"
            android:textStyle="bold"
            android:textSize="20sp" />

        <ImageView
            android:id="@+id/iv_picture"
            android:layout_width="wrap_content"
            android:layout_height="400dp"
            android:maxHeight="700dp"
            android:padding="10dp"
            android:src="@drawable/picture" />

        <RatingBar
            android:id="@+id/ratings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="20dp"
            android:numStars="5"
            android:rating="4.5"
            android:stepSize="1.0 "/>

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginBottom="20dp"
            android:text="Submit"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/tv_score"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_margin="10dp"
            android:text="SCORE : "
            android:textColor="@color/black"
            android:textSize="20sp" />
    </LinearLayout>

</LinearLayout>

내가만든 작품에 평점을 주기 위해 필요한 부분에 각각의 id를 부여한다.

레이아웃에는 이미지뷰, 레이팅바, 버튼, 텍스트뷰를 적절히 배치하여 작성한다.

 

3) MainActivity.java

레이아웃 구성이 완료되었으니 이번에는 자바코드를 작성한다.

다음과 같이 자바코드를 작성한다.

public class MainActivity extends AppCompatActivity {

    TextView tvScore;
    Button btnSubmit;
    RatingBar ratingBar;

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

        initView();
    }

    private void initView() {
        btnSubmit = findViewById(R.id.button);
        tvScore = findViewById(R.id.tv_score);
        ratingBar = findViewById(R.id.ratings);

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float rating = ratingBar.getRating();
                tvScore.setText(String.valueOf("SCORE : " + rating));
            }
        });

    }
}

사용하는 이미지의 경우 딱히 변경되는 것이 없이 보는 것 뿐이기에 딱히 id를 찾아 연결해주지 않아도 된다.

레이팅바를 드래그 또는 터치하여 별점을 선택한 후 버튼을 눌렀을 때 반응하여 스코어 텍스트에 표시되는 것이 전부이므로 버튼, 텍스트뷰, 레이팅바에 대한 id값만 연결해주면 된다. 


3. 실행 결과

작성한 레이팅바 테스트 앱을 실행해보면 다음과 같이 구동되는 것을 확인할 수 있다.

구현하고자 했던대로 평가한 평점대로 하단의 SCORE : 옆에 점수가 표시되는 것을 확인할 수 있다.

내가 만든 이미지 작품으로 아주 만족스러우므로 5.0점을 주도록 하겠다ㅎ

gif 파일로 변경하면 이상하게 화면이 깨지는 현상이 있지만 실제 앱에서는 전혀 깨지지 않는다.

어쨋거나 구현하고자 하는대로 구현 완료!

반응형

댓글