我将attributeset添加到这样的自定义组件:
<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>
Run Code Online (Sandbox Code Playgroud)
我可以通过从类型化数组中询问它来获取每个枚举的值:
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();
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要枚举的实际名称,而不是值,该怎么办?我怎么能在代码中得到它?请帮忙
更新 我这样做的主要原因是我可以在不同的情况下重用这个组件,并对layout 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" …Run Code Online (Sandbox Code Playgroud)