我正在使用微调器将值显示为下拉列表,我正在使用以下代码更改微调器文本值
<Spinner
android:id="@+id/showUnit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:entries="@array/unitName"
android:background="@drawable/gradient_spinner_map_miles_button" />
showUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = arg0.getItemAtPosition(arg2).toString();
if (arg1 != null && arg1 instanceof TextView) {
((TextView)arg1).setTextColor(Color.WHITE);
((TextView) arg1).setTextSize(13);
((TextView) arg1).setGravity(Gravity.CENTER);
}
showUnit = (Spinner) findViewById(R.id.showUnit);
但是当我尝试旋转屏幕时,((TextView)arg0.getChildAt(0))
返回 null。
我知道当我在横向或纵向模式下旋转屏幕时, Activity 周期会重新启动,那么为什么微调器会变空。
请给我合适的解决方案。
谢谢
最佳答案
当您在 View arg1
中有适当的 View 时,为什么要使用 getChildAt
?
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
if (arg1 != null && arg1 instanceof TextView) {
((TextView)arg1).setTextColor(Color.WHITE);
}
}
要更改微调器中选定文本的颜色,最好使用选择器。
spinner_state.xml(在 drawable 文件夹中)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@color/black" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@color/red" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@color/red" />
<item
android:state_enabled="true"
android:drawable="@color/gray" />
</selector>
在你的微调器中,应用选择器:
android:dropDownSelector="@drawable/spinner_state"
微调器来源:Spinner does not apply dropDownSelector attribute
它没有解释为什么您的值在 onItemSelected
中为空,但如果没有您的完整代码,我看不出有什么问题。
关于旋转屏幕后,Android 微调器变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21016332/