【问题标题】:Android Spinner Array Adapter Null Pointer ExceptionAndroid Spinner 数组适配器空指针异常
【发布时间】:2014-11-12 21:13:09
【问题描述】:

我目前正在使用如下所示的字体列表创建微调器。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_custom_style_dialog, container, false);

    mSpinnerFont = (Spinner) getActivity().findViewById(R.id.spinnerFont);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item,
            new String[] {"System Font", "Helvetica", "Helvetica-Neue", "Impact"});
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mSpinnerFont.setAdapter(arrayAdapter);

    return view;
}

但是,它在最后一行抛出了一个空指针异常。我不明白数组如何具有空值。感谢您的回复。

下面的微调器 XML

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.richluick.blocnotes.CustomStyleDialogFragment">


    <Spinner
        android:id="@+id/spinnerFont"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</FrameLayout>

【问题讨论】:

  • 也许 mSpinnerFont 为空!!检查 id "R.id.spinnerFont" 是否与您的 xml 文件相同?
  • 我在上面发布了 XML。在我看来是一样的
  • 通过调试或将其值写入控制台来检查您的 mSpinnerFont 是否为空。如果是这样,您可能有一个身份问题需要追查。
  • 显然 mSpinnerFont 确实为空。可能你没有调用 setCurrentView,或者当前视图包含一些其他的 XML,而不是你认为的
  • @Mixaz 我添加了完整的 onCreateView 方法以供参考。它在一个片段内。那里一切似乎都还好?

标签: android nullpointerexception spinner android-arrayadapter android-spinner


【解决方案1】:

这一行:

getActivity().findViewById(R.id.spinnerFont);

从与活动关联的根视图中查找视图(由 Activity.setCurrentView() 设置),而您的微调器位于您刚刚从文件中膨胀的视图内(它未放置到Activity 的视图层次结构尚未)。将您的代码修复为:

view.findViewById(R.id.spinnerFont);

【讨论】:

    【解决方案2】:

    1) 我已经删除了

    xmlns:tools="http://schemas.android.com/tools"
    

    tools:context="com.richluick.blocnotes.CustomStyleDialogFragment"
    

    我测试了你的代码,它运行良好!我想问题出在

    xmlns:tools="http://schemas.android.com/tools"
    

    试着改成

    xmlns:tools="http://schemas.android.com/apk/res-auto"
    

    2) 如果您的问题没有解决,可能是您的 FrameLayout 未包含在活动视图中。所以

      getActivity().findViewById(R.id.spinnerFont); 
    

    将始终返回Null

    【讨论】:

    • #1 仍然对我不起作用。如何确定 FrameLayout 包含在内?
    • 向你的框架添加一个 id(在 xml 中),并调用 getActivity().findViewById(R.id.YOUR_ID) 以获取代码中的视图
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2017-01-30
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多