首页 > 解决方案 > 为什么在 onCreate() 方法中初始化 Array Adapter 很重要?

问题描述

ArrayAdapter<String> bigSquash = new ArrayAdapter<String>(this, R.layout.adapter_xml, onPointString);

每当我在 onCreate() 方法之外初始化这个数组适配器时,就会生成一个错误,而当我在 onCreate() 方法中初始化它时,不会引发错误。那么有人能告诉我为什么会这样吗?

标签: androidandroid-layoutandroid-recyclerviewandroid-arrayadapteroncreate

解决方案


ArrayAdapter构造函数中会调用LayoutInflater.from(context) 如果activity没有onCreate,就会跑出异常,

ArrayAdapter 构造函数代码

private ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
        @IdRes int textViewResourceId, @NonNull List<T> objects, boolean objsFromResources) {
    mContext = context;
    mInflater = LayoutInflater.from(context);
    mResource = mDropDownResource = resource;
    mObjects = objects;
    mObjectsFromResources = objsFromResources;
    mFieldId = textViewResourceId;
}

LayoutInflater.from 代码

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

activity.getSystemService 代码

@Override
public Object getSystemService(@ServiceName @NonNull String name) {
    if (getBaseContext() == null) {
        throw new IllegalStateException(
                "System services not available to Activities before onCreate()");
    }

    if (WINDOW_SERVICE.equals(name)) {
        return mWindowManager;
    } else if (SEARCH_SERVICE.equals(name)) {
        ensureSearchManager();
        return mSearchManager;
    }
    return super.getSystemService(name);
}

所以需要在activity onCreate之后调用。</p>


推荐阅读