2015-03-31 58 views
2

我試圖通過Pedram從this答案實施更新的解決方案,但我不知道要創建一個新的實例CircleProgressBar。它需要AttributeSet作爲參數傳遞,但如何獲取它?如何通過AttributeSet作爲參數

CircleProgressBar circleProgressBar = new CircleProgressBar(MainActivity.this, ?); 

回答

1

當一個視圖被通過在XML定義的佈局充氣AttributeSet構造被使用。如果你在代碼中構造一個,你應該使用單參數構造函數(例如new CircleProgressBar(MainActivity.this))。如果單參數構造函數沒有定義,你只需要添加它。如果你希望能夠完全從Java代碼中構建它,你只需要爲屬性添加一些getter/setter。

可替換地,只用一個單一的項目定義佈局XML(例如名稱view_progress_circle.xml):

<com.your.packagename.CircleProgressBar 
    android:layout_width="100dp" 
    android:layout_height="100dp" 
    // etc. add other attributes here 
    /> 

然後,在代碼,以創建:

CircleProgressBar bar = (CircleProgressBar) LayoutInflater.from(MainActivity.this) 
     .inflate(R.layout.view_progress_circle, parent, false): 

其中parentViewGroup你將把視圖附加到。