我添加屬性集中到一個自定義組件這樣得到枚舉:屬性集,名字
<declare-styleable name="MySeekBarWidget">
<attr name="type">
<enum name="money" value="1" />
<enum name="percent" value="2" />
<enum name="time" value="3" />
<enum name="money_frequency" value="4" />
<enum name="money_percent_or_fixed" value="5" />
<enum name="money_month" value="6" />
<enum name="time_year_only" value="7" />
</attr>
</declare-styleable>
我可以要求它從類型數組得到每個枚舉值:
public MySeekBarWidgetLayout(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MySpinnerContainer);
type = array.getInt(R.styleable.MySeekBarWidget_type,1);
array.recycle();
}
但是如果我想要枚舉的實際名稱而不是值。我如何獲得代碼?請幫助
UPDATE 我這樣做的主要原因是,這樣我可以重複使用在不同情況下該組件並有佈局XML定義如下每個情況不同的規則:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:app1="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="@+id/autoCalculatorAmountMySeekBarWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/autoCalculatorMyDateView"
android:layout_marginLeft="@dimen/side_margin"
android:layout_marginRight="@dimen/side_margin"
android:layout_marginTop="@dimen/top_spacing"
android:tag="@string/amount"
app:max="@integer/a_million"
app:type="money"
class="customComponents.MySeekBarWidget"/>
<view
android:id="@+id/autoCalculatorInterestMySeekBarWidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/autoCalculatorAmountMySeekBarWidget"
android:layout_marginLeft="@dimen/side_margin"
android:layout_marginRight="@dimen/side_margin"
android:layout_marginTop="@dimen/top_spacing"
android:tag="@string/interest_rate"
app:max="@integer/fifty"
app:type="percent"
class="customComponents.MySeekBarWidget"/>
</RelativeLayout>
如您所見,每個組件「MyseekBarWidget」具有不同的類型(百分比與金錢)。這將觸發不同的規則。 但是當我打電話找出類型時,我只能得到枚舉的值。我希望這個名字能夠使代碼更簡潔。我可以這樣寫:
if(type==money)...;
與書面方式:
if(type==1)..;
這使得代碼更難調試/瞭解
我已更新我的答案以顯示完整圖片。您的解決方案絕對是值得考慮的事情,只是想確保沒有更清潔/更優雅的解決方案 – mrseanpaul81
@ mrseanpaul81好的,請檢查我在答案底部添加的內容。 – Korcholis
您的解決方案無法正常工作。你在哪裏做'array.getInt(...,Type.Money)'是錯誤的。你需要顯式地'Type.Money.getValue()' –