繁体   English   中英

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

[英]How to add a Rating Bar programmatically

如何以编程方式在Android中添加评分栏? 以及如何设置星数。 有时即使我设置了星星数也不会出现在ui中。

关键是包装内容

// 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>

您可以尝试一些库来制作等级栏。.例如https://github.com/DreaminginCodeZH/MaterialRatingBar

要以编程方式添加评分栏,您需要添加以下代码

//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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM