반응형

배달앱이나 여러 쇼핑사이트들에서 흔히 볼 수 있는 평점 다는 기능을 (별점) ratingbar로 구현 해보았다.

(1) MainActivity.java

package com.example.ratingapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView2;
    RatingBar ratingBar;
    String str;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ratingBar = findViewById(R.id.ratingBar);
        textView2 = findViewById(R.id.textView2);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                Toast.makeText(getApplicationContext(),"New Rating: "+ rating, Toast.LENGTH_SHORT).show();
                str = String.valueOf(rating);
                str = Float.toString(rating);
                textView2.setText(str);
            }
        });
    }
}

결과 텍스트의 rating에서 얻은 값을 넣고 싶어서 float형을 string형으로 바꾸었다. 

-> float 형을 string으로 바꾸는 법

str = String.valueOf(rating);
str = Float.toString(rating);

(2) activity_main.xml

<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#C11515"
        android:numStars="5"
        android:stepSize="1.0" />

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

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="평점은: "
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:hint="결과"
            android:textSize="20dp" />
    </LinearLayout>

</LinearLayout>

평점 어플

 

반응형

+ Recent posts