旋转后微调器值消失

Posted

技术标签:

【中文标题】旋转后微调器值消失【英文标题】:Spinner values dissapear after rotation 【发布时间】:2021-10-02 17:50:29 【问题描述】:

我*有一个简单的“材质微调器”实现:

<com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
    android:layout_ 
    android:layout_>

    <AutoCompleteTextView
        android:id="@+id/filled_exposed_dropdown"
        android:layout_
        android:layout_
        android:inputType="none"/>

</com.google.android.material.textfield.TextInputLayout>

以及填充列表的我的片段 onCreate 方法

AutoCompleteTextView editTextFilledExposedDropdown;
ArrayAdapter<String> adapter = null;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) 
    String[] type = new String[] "Bed-sitter", "Single", "1- Bedroom", "2- Bedroom","3- Bedroom";
    adapter =new ArrayAdapter<>( getContext(),R.layout.dropdown_menu_popup_item, type);
    editTextFilledExposedDropdown = view.findViewById(R.id.filled_exposed_dropdown);
    editTextFilledExposedDropdown.setAdapter(adapter);

只要我不选择项目并旋转手机,代码就可以正常工作。 一旦我旋转手机,onCreate 方法就会再次被调用,但由于某种原因,唯一可用的项目是我之前选择的项目。 菜单不显示所有其他项目。

原因可能是什么? 我故意重新填充 arrayadapter,以确保在旋转手机时使用相同的对象。

【问题讨论】:

尝试设置editTextFilledExposedDropdown.setFreezesText(false); @Zain unfourtantly that didn't work :/. 【参考方案1】:

使用自定义视图。这是材料设计类中的一个错误,尚未修复:

public class ExposedDropdownMenu extends MaterialAutoCompleteTextView 

    public ExposedDropdownMenu(@NonNull @NotNull Context context) 
        super(context);
    
    public ExposedDropdownMenu(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attributeSet) 
        super(context, attributeSet);
    


    public ExposedDropdownMenu(@NonNull @NotNull Context context, @Nullable @org.jetbrains.annotations.Nullable AttributeSet attributeSet, int defStyleAttr) 
        super(context, attributeSet, defStyleAttr);
    

    @Override
    public boolean getFreezesText() 
        return false;
    

【讨论】:

【参考方案2】:

在onResume()方法中设置适配器,就可以正常工作了。

@override
public void onResume()
    super.onResume()
    String[] type = new String[] "Bed-sitter", "Single", "1- Bedroom", "2- Bedroom","3- Bedroom";
    adapter =new ArrayAdapter<>( getContext(),R.layout.dropdown_menu_popup_item, type);
    editTextFilledExposedDropdown = view.findViewById(R.id.filled_exposed_dropdown);
    editTextFilledExposedDropdown.setAdapter(adapter);l̥

【讨论】:

以上是关于旋转后微调器值消失的主要内容,如果未能解决你的问题,请参考以下文章

屏幕旋转后按钮消失

旋转后recyclerview行中的图像消失

UISplitViewController Detail View 旋转后消失

UIBarButtons 带有系统项的样式,旋转后消失

选择微调器值时,android应用程序停止工作

带有图像视图、2 个标签、按钮的自动布局 - 标签在旋转后消失