Java 안드로이드
4. 기본 컨트롤 – 9. RatingBar
언휴
2025. 1. 4. 08:06
이번에는 별점을 부여할 때 많이 사용하는 RatingBar를 이용한 간단한 실습을 합시다.

먼저 activity_main.xml 파일에 컨트롤을 배치합시다. 최상위 요소는 LinearLayout을 배치하세요.
그리고 자식으로 RatingBar와 TextView를 배치합시다. RatingBar의 stepSize 속성은 변경할 수 있는 최소 간격입니다. 그리고 isIndicator 속성은 사용자에 의해 rating 값을 변경 가능 여부입니다. 주의할 점은 false일 때 사용자에 의해 변경할 수 있다는 것입니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.ehclub.ex_ratingbar.MainActivity"
android:orientation="vertical">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ratbar"
android:stepSize="0.1"
android:isIndicator="false"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textColor="#FF0000"
android:text="0"
android:id="@+id/tv"/>
</LinearLayout>
이제 MainActivity.java 파일을 편집합시다. onCreate 메서드에 findViewById 메서드를 호출하여 RatingBar 개체를 참조합니다.
RatingBar rb = (RatingBar) findViewById(R.id.ratbar);
그리고 RatingBar의 값 변경 리스너를 등록하세요. 리스너에서는 TextView 개체를 참조하여 rating 값을String 형식으로 변환하여 text 속성을 설정합니다.
rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(String.valueOf(rating));
}
});
다음은 MainActivity.java 파일의 내용입니다.
package com.example.ehclub.ex_ratingbar;
import android.media.Rating;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RatingBar rb = (RatingBar) findViewById(R.id.ratbar);
rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(String.valueOf(rating));
}
});
}
}
언제나휴일 추천 여행 및 산책