如何以编程方式添加评级栏

时间:2018-05-31 20:12:13

标签: android android-layout android-studio

如何以编程方式添加评分栏android? 以及如何设置星星的数量。有时即使我设定它不会出现在ui中的星数。

3 个答案:

答案 0 :(得分:1)

关键是包装内容

// first create a layout 
LinearLayout ll = new LinearLayout(getApplicationContext());
// now you will have to set width and height 
ll.setMinimumWidth(300);
ll.setMinimumHeight(100);
// now init Rating bar
RatingBar rb = new RatingBar(getApplicationContext());
// now set num of stars
rb.setNumStars(5);
// adding ratingBar into the created layout
ll.addView(rb);
// get the current layout
LinearLayout l = findViewById(R.id.linearLayout);
// now add the layout
l.addView(ll);

这是布局资源

<?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=".MainActivity"
    android:orientation="horizontal"
    android:id="@+id/mainLayout">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</LinearLayout>

答案 1 :(得分:1)

你可以尝试一些liblary来制作评级栏..就像https://github.com/DreaminginCodeZH/MaterialRatingBar

一样

答案 2 :(得分:1)

要以编程方式添加评级栏,您需要添加此代码

//parent layout in which you want to add rating bar
LinearLayout linearLayout = findViewById(R.id.d_layout);
RatingBar r = new RatingBar(MainActivity.this);
linearLayout.addView(r);
//how many starts you want to show,parent layout width must be wrap_content
r.setNumStars(6);
r.setRating(Float.parseFloat("1.5"));