场景
效果
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
实现
将布局改为LinearLayout,并通过android:orientation="vertical">设置为垂直布局,然后添加一个ratingBar,并通过
android:rating="5"
设置其星数为5
<?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=".ratingBaractivity"> <ratingBar android:id="@+id/ratingBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:rating="5" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FF5000" android:text="发表评价" /> </LinearLayout>
然后来到Activity,通过Id获取ratingBar和Button,在button的点击事件中,获取星级数,并提示。
packagecom.badao.relativelayouttest; importandroidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ratingBar; importandroid.widget.Toast; public class ratingBaractivity extends AppCompatActivity { private ratingBarratingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rating_bar); ratingBar = (ratingBar) findViewById(R.id.ratingBar); Button button = (Button) findViewById(R.id.btn); button.setonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { float rating = ratingBar.getrating(); Toast.makeText(ratingBaractivity.this,"你的评分为:"+rating+"分",Toast.LENGTH_SHORT).show();; } }); } }