android - 为什么在 onCreate() 方法中初始化 Array Adapter 很重要?
问题描述
ArrayAdapter<String> bigSquash = new ArrayAdapter<String>(this, R.layout.adapter_xml, onPointString);
每当我在 onCreate() 方法之外初始化这个数组适配器时,就会生成一个错误,而当我在 onCreate() 方法中初始化它时,不会引发错误。那么有人能告诉我为什么会这样吗?
解决方案
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>
推荐阅读
- r - DF 作为矩阵的总结
- reactjs - React.js:如何访问私有路由中的 URL 参数
- sql - 在以下程序中将结束日期声明为当前日期?
- erlang - 应该在哪里重新启动“simple_one_for_one”的孩子?
- java - java - 如何通过传递存储桶名称和文件名从Java中的minio服务器下载多个文件
- c++ - 从一个程序的 cout 读取一系列整数到 C++ 中另一个程序的 cin
- c# - 在 CassandraCSharpDriver.Graph 中使用 SimpleGraphStatement 的树查询抛出“无法转换为 org.apache.tinkerpop.gremlin.structure.Element”
- fusioncharts - 更改 FusionChart 地图需要去掉颜色范围滑块中的橙色背景色
- php - 使用 php mail() 发送多个附件
- aws-cdk - 如何测试 CDK 上下文键是否存在?