不能在Android中使用getLayoutInflater()

时间:2016-03-15 09:24:45

标签: android

如果我的代码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);
}

3 个答案:

答案 0 :(得分:1)

更改以下行

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );

这是因为,ServiceContext。服务范围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);

两者都有效,因为ServiceContext