android自定義ratingbar,靈活性極高

XLhRatingBar

一個自定義的android RatingBar,無固定樣式,一切由你指定。

image

https://github.com/xingliuhua/XLHRatingBar歡迎點擊star。

背景

我們常常要使用到RatingBar來做一些評分、進度、等級功能。android.widget.RatingBar可以實現一些簡單效果,我們可以利用

layer-list和android:progressDrawable。我們還可以放置一些圖片,當點擊的時候改變圖片的樣式來實現。

我們如果想實現一些復雜的效果,這些方案就有點麻煩了:

  • 每次半顆星

  • 每顆星的大小不一

  • 第1、3、5是半顆,第2、4、6是整顆

  • 豎向或者斜向放置

他們都顯得那么笨重,不夠靈活,擴展性也非常差。

功能

  • 每個內部單元控件(就是星星)有三種狀態:未選中、選中一半、全選中。

  • 內部單元控件的選中狀態由用戶在回調中根據點擊的位置自己判斷。

  • 自定義每個內部單元控件的樣式,用戶可根據單元控件的位置、狀態動態返回控件。

  • 自定義屬性或代碼設置內部單元控件的總數,已選個數。

  • 選中狀態的監聽。

安裝


dependencies {

//other dependencies...

compile 'com.xingliuhua:xlhratingbar_lib:4.0'

}

使用

SimpleRatingView

該庫以及默認實現了簡單的樣式及功能,默認共5顆星,每次最小可以改變半顆??梢灾苯釉诖a或xml文件中使用。


XLHRatingBar xlhRatingBar = new XLHRatingBar(this);

//添加到容器布局中即可

或者在xml布局中


android:layout_width="match_parent"

android:layout_height="wrap_content"

app:numStars="5"

app:rating="2.5" />

自定義樣式

實現接口IRatingView

IRatingView就是單個內部控件的行為抽象,你可以根據自己的業務需求來返回對應的值,可以參考SimpleRatingView默認實現。


public interface IRatingView {

/**

* you can change your item style by state and position. eg:color,text size.

* @param state STATE_NONE,STATE_HALF,STATE_FULL

* @param position star index. start from 0

* @param starNums star item number

*/

void setCurrentState(int state,int position,int starNums);

/**

* return you start item view,you can custom item by positon

* @param context

* @param position star index. start from 0

* @param starNums star item number

* @return

*/

ViewGroup getRatingView(Context context,int position,int starNums);

/**

* not selected

*/

public static final int STATE_NONE = 0;

/**

* select half

*/

public static final int STATE_HALF = 1;

/**

* selected

*/

public static final int STATE_FULL = 2;

}

在布局中引用并指定IRatingView的實現類。


xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center_vertical"

app:numStars="5"

app:rating="5"

app:ratingViewClass="com.example.xlhratingbar_lib.SimpleRatingView"

/>

代碼中使用


LinearLayout llContainer = (LinearLayout) findViewById(R.id.ll_container);

XLHRatingBar xlhRatingBar = new XLHRatingBar(this);

xlhRatingBar.setNumStars(3);

xlhRatingBar.setEnabled(false);//can not change rating by touch

xlhRatingBar.setRatingViewClassName("com.example.xlhratingbar.MyRatingView4");

xlhRatingBar.setOnRatingChangeListener(new XLHRatingBar.OnRatingChangeListener() {

@Override

public void onChange(float rating, int numStars) {

Toast.makeText(getApplicationContext(), "rating:" + rating, 0).show();

}

});

llContainer.addView(xlhRatingBar);

歡迎大家點擊star。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。