如果我的代码extends AppCompatActivity
:
View uploadProgressView = getLayoutInflater().inflate(R.layout.view_upload_progress, null);
UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);
我可以使用getLayoutInflater()
,但当我更改为extends Services
时,它无效。
我正在研究Stackoverflow
from this post并收到答案并更改为:
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View uploadProgressView = inflater.inflate(R.layout.view_upload_progress, null);
UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);
但它不起作用,如何使用getLayoutInflater()
?
此抛出异常:
java.lang.NullPointerException
CallRecordService.addUploadToList(CallRecordService.java:167)
第一行错误LayoutInflater inflater = ......
Context context;
private void addUploadToList(String uploadID, String filename) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View uploadProgressView = inflater.inflate(R.layout.view_upload_progress, null);
UploadProgressViewHolder viewHolder = new UploadProgressViewHolder(uploadProgressView, filename);
viewHolder.uploadId = uploadID;
container.addView(viewHolder.itemView, 0);
uploadProgressHolders.put(uploadID, viewHolder);
}
答案 0 :(得分:1)
更改以下行
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
到
LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
这是因为,Service
是Context
。服务范围ContextWrapper
延伸Context
。你也可以使用这个'服务中的关键字。
答案 1 :(得分:0)
使用WindowManager
扩充视图后,您需要将布局添加到LayoutManager
。
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(view, getLayoutParams());
答案 2 :(得分:0)
如果您在扩展Service
的课程中,可以使用
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
或
LayoutInflater inflater = LayoutInflater.from(this);
两者都有效,因为Service
是Context