我根据AppCompatSpinner
编写了我的微调器。
我想得到条目和引力。这是我的代码:
public class RxSpinner extends AppCompatSpinner {
private static final int[] RX_SPINNER_OVERRIDE_ATTRS = {
android.R.attr.entries,
android.R.attr.gravity
};
public RxSpinner(Context context) {
super(context);
}
public RxSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RxSpinner);
final int textColor = a.getColor(R.styleable.RxSpinner_text_color, context.getResources().getColor(R.color.gray_dark));
final int dropdownTextColor = a.getColor(R.styleable.RxSpinner_dropdown_text_color, context.getResources().getColor(R.color.gray_dark));
final float textSize = a.getDimension(R.styleable.RxSpinner_text_size, context.getResources().getDimension(R.dimen.text_normal));
a.recycle();
a = context.obtainStyledAttributes(attrs,RX_SPINNER_OVERRIDE_ATTRS);
if (a.hasValue(0)){
CharSequence[] entries = a.getTextArray(0);
final int gravity = a.getInt(1, Gravity.CENTER); // here is the problem always default value.
//create adapter
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.item_spinner_top, R.id.text, entries) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text = ButterKnife.findById(view, R.id.text);
text.setTextColor(textColor);
text.setTextSize(DimenUtils.px2dp(textSize));
text.setGravity(gravity);
return view;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View dropDownView = super.getDropDownView(position, convertView, parent);
TextView text = ButterKnife.findById(dropDownView, R.id.text);
text.setTextColor(dropdownTextColor);
text.setTextSize(DimenUtils.px2dp(textSize));
text.setGravity(gravity);
return dropDownView;
}
};
adapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
setAdapter(adapter);
}
a.recycle();
//set background tint
ViewCompat.setBackgroundTintList(this, ColorStateList.valueOf(textColor));
}
}
我只能获得条目而不是引力。
看起来模式相同,任何人都可以告诉我为什么?
我知道还有其他方法可以获得引力,但我对原因更感兴趣。
答案 0 :(得分:1)
我自己找到了原因。 它在appcompat-v7包中被覆盖。
<declare-styleable name="Spinner"><attr format="reference" name="prompt"/><attr format="enum" name="spinnerMode"><enum name="dialog" value="0"/><enum name="dropdown" value="1"/></attr><attr name="android:dropDownSelector"/><attr name="android:popupBackground"/><attr name="android:dropDownVerticalOffset"/><attr name="android:dropDownHorizontalOffset"/><attr name="android:dropDownWidth"/><attr format="reference" name="popupPromptView"/><attr name="android:gravity"/><attr format="boolean" name="disableChildrenWhenDisabled"/><attr name="android:background"/></declare-styleable>
所以你可以用这种方式获得价值:
a = context.obtainStyledAttributes(attrs,android.support.v7.appcompat.R.styleable.Spinner);
final int gravity = a.getInt(android.support.v7.appcompat.R.styleable.Spinner_android_gravity,Gravity.CENTER);
a.recycle();