解决“getLayoutInflater(未定义)”错误

3

在使用以下代码编译程序时,出现了一个错误。它说getLayoutInflater()未定义。我该如何解决?

 final LayoutInflater inflater = getLayoutInflater ( ); 

请放置一些源代码和错误日志。 - Mojo Risin
愚蠢的问题,不过。您是否忘记扩展 Activity 类?此外,更多代码会更好。 - George
尝试接受满意的答案。这将增加有人回复您未来问题的机会,也将有助于整个社区。 - Ewoks
4个回答

18

嗨,Prasanth,你可以尝试这个方法:

步骤1:创建一个布局膨胀器对象,如下所示:

LayoutInflater mInflater;

第二步:通过传递上下文进行初始化

Context context=MyActivity.getApplicationContext();
mInflater = LayoutInflater.from(context);

第三步:在getView()方法中,您可以将视图初始化为

public View getView(int arg0, View myView, ViewGroup parent) {


            if (convertView == null) {

myView = mInflater.inflate(R.layout.mytest, null);
}

1

据我所知,getLayoutInflater()是由Context提供的一个方法。如果这行代码位于不继承自Context的类中,则无法正常工作。传递一个Context对象并在该对象上调用该方法。

编辑:对不起,我看了api文档,它是由Activity提供的。


1
这是我的做法: 在我的活动代码中,我将上下文作为参数传递给我的适配器,像这样:
CustumAdapter myAdapter = new CustumAdapter(this, Items);

然后我可以像这样在我的适配器中使用它:

public class CustumAdapter extends BaseAdapter {

ArrayList<ListItem> Items ;
public Context context;

public CustumAdapter(Context context, ArrayList<ListItem> Items) {
    this.Items = Items;
    this.context = context;
}
....
@Override
public View getView(int position, View convertView, ViewGroup parent) {        
    LayoutInflater myInflater = LayoutInflater.from(context);
    View myview = myInflater.inflate(R.layout.row_item,null);

所有工作都正常 :)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接