旋转屏幕后,Android 微调器变为空

标签 android null android-spinner

我正在使用微调器将值显示为下拉列表,我正在使用以下代码更改微调器文本值

<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/

相关文章:

android - Facebook api 无效的应用 ID

android - Polymer 是否支持较低的 Android 版本?

java - MySQL 连接器与 Android Studio

Android:手机摄像头分辨率会影响预处理结果吗

c - 为什么当 current->next == NULL 时 current = current->next 会出现段错误?

Postgresql - 求和时如何将 NaN 视为 0?

java - 尝试在空对象引用上调用虚拟方法 'java.lang.String java.lang.Integer.toString()'

android - 如何自动禁用 Spinner 上的 OnClick 事件?

java - 旋转器不起作用 setOnItemSelectedListener

android - 在点击 View 下方显示下拉列表