使用Anko的自定义评级栏

时间:2018-04-23 15:59:16

标签: android kotlin anko

我一直在使用Anko和Kotlin探索Android开发,并且在评级栏上遇到了一些问题,即它的大小。我尝试使用自定义样式将其缩小,但是themedRatingBar似乎不起作用。所以我选择制作自定义评级栏。当我在主要活动中以这种方式设置它时,我似乎无法按照我想要的方式工作:

  

starRatingView {

     

setRating(3)

     

}

它不输出等级3,而是输出默认等级,即零。

  

类StarRatingView:_LinearLayout {

lateinit var imageViewStars: List<ImageView>
private var starNum: Float = 0f
private var starSize: Int = 5

constructor(context: Context): super(context) {
    initializeView()
}

fun initializeView() {
    with(this) {
        linearLayout {
            relativeLayout {
                linearLayout {
                    for (i in 1..starSize)
                        imageView(R.drawable.ratingbar_empty)
                }
                linearLayout {
                    for (i in 0..Math.round(starNum)) {
                        imageView(R.drawable.ratingbar_filled)
                    }
                }
            }
        }
    }
}

fun setSize(starSize: Int){
    this.starSize = starSize
}

fun setRating(starNum: Float){
    this.starNum = starNum
}
     

}

以上是我用来创建自定义RatinBar的代码。尽量避免使用XML,而是使用Anko。

1 个答案:

答案 0 :(得分:0)

如果我能在这里提供帮助,可以使用Anko库和Kotlin代码在自定义Alert中显示自定义RatingBar ...

var rateGave: String? = null
alert {
        title = "Rate your experience"
        customView {
            linearLayout {
                ratingBar {
                    numStars = 5 //here is to define the number of stars you want
                    rating = 4f //starting rate to show as the alert pop up
                    setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
                        rateGave = rating.toString()
                    }
                }
            }
        }
        positiveButton("Rate") { rate() }
    }.show()
}

fun rate() {
    println(rateGave) //now it's just printing out the rate to show that it's working fine, but in this function you can mange all the operations you need with the rating value
}

希望它有用。 祝你有愉快的一天:)