首先用到的控件是RatingBar,一般都很少用系統原生的,都是給出了自己用的UI星圖,所以我們要做一些準備工作的
首先看看異常顯示
如果給RatingBar設置固定的高度會導致星星顯示不全,或者顯示異常,這樣子很醜,網上看過很多博客,試過了,各種辦法都不太友好
就算在調試的這臺手機上顯示正常,更換個其他分辨率的手機就會出現顯示不全,或者不夠撐滿控件的大小,所以給出了以下解決方案:獲取星星圖片的原圖大小,然後通過代碼進行設置RatingBar的高度
先看看更改具體效果,首先放了兩個系統的,一個是自適應高度,一個是指定高度,第三個是自定義背景的RatingBar,具體效果圖如下:
具體步驟如下:
首先xml文件中放3個RatingBar<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RatingBar
android:id="@+id/rb1"
android:numStars="5"
android:rating="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RatingBar
android:id="@+id/rb2"
android:numStars="5"
android:rating="3"
android:layout_width="wrap_content"
android:layout_height="30dp" />
<RatingBar
android:layout_marginTop="20dp"
android:id="@+id/rb3"
style="@style/FiveStarsStyle1"
android:numStars="5"
android:rating="3"
android:layout_width="wrap_content"
android:layout_height="30dp" />
</LinearLayout>
第三個是定義背景的RatingBar,在style文件中定義
<!--五星控件 start-->
<style name="FiveStarsStyle1" parent="@android:style/Widget.Holo.RatingBar.Small">
<item name="android:progressDrawable">@drawable/five_rating_bar</item>
<item name="android:minHeight">40dp</item>
<item name="android:maxHeight">40dp</item>
</style>
<!--五星控件 end-->
星星進度的背景圖片也是xml定義的drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background"
android:drawable="@drawable/stars_gray" />
<item
android:id="@android:id/secondaryProgress"
android:drawable="@drawable/stars_gray" />
<item
android:id="@android:id/progress"
android:drawable="@drawable/stars_bright" />
</layer-list>
兩個小圖標呢就是自己找的資源了
解決星星圖片不能填充控件的關鍵代碼:
package com.example.mytestdemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.RatingBar;
public class StarsActivity extends AppCompatActivity {
RatingBar rb3;
private int starsImgHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stars);
rb3 = (RatingBar) findViewById(R.id.rb3);
//獲取圖片的高度
try {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.stars_bright);
starsImgHeight = bmp.getHeight();
} catch (Exception e) {
e.printStackTrace();
}
//將獲取的圖片高度設置給RatingBar
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)rb3.getLayoutParams();
lp.width = LinearLayout.LayoutParams.WRAP_CONTENT;
lp.height =starsImgHeight;
rb3.setLayoutParams(lp);
}
}
主要還一開始說的思想,獲取圖片的高度設置給RatingBar,目前就這個解決方案了,如果大家有更好的方案,請給我留言哈,大家一起學習進步