关于Java:从ApplicationContext获取一个布局填充器

Get a layout inflater from the ApplicationContext

我正在遵循该指南来实现自定义首选项。 http://android-journey.blogspot.com/2010/01/for-almost-any-application-we-need-to.html。在方法

1
2
3
4
@Override
protected View onCreateView(ViewGroup parent){
   ...
}

该指南以编程方式创建元素,然后返回视图。我想从xml文件中检索布局。但是调用getLayoutInflater()是不可行的,在那我该如何检索布局填充器以获取存储在文件" progressbarpreference.xml"中的视图?

如果需要,我可以静态引用应用程序上下文

谢谢


1
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Service.LAYOUT_INFLATER_SERVICE);

应该可以解决问题(在这种情况下,ctx是您的应用程序上下文)。


1
2
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.yourcustomviewxml, layout);

我问了一个问题:如何将AttributeSet传递给自定义视图。谢谢Ian!


使用静态引用,假设它是上下文。

1
rowLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.progress_bar, parent, false);

,其中progress_bar是线性布局的ID。