问题描述
我正在研究John Horton的 Android初学者编程,目前正在尝试创建一个笔记应用程序。 Horton刚刚推出了 ListViews
。但是,我在使用适配器
类
时遇到问题:
I am working through John Horton's Android Programming for Beginners, and am currently attempting to create a note-taking app. Horton has just introduced ListViews
. However, I am having trouble with the adapter
class
:
public class NoteAdapter extends BaseAdapter {
List<Note> mNoteList = new ArrayList<Note>();
@Override
public int getCount(){
return mNoteList.size();
}
@Override
public Note getItem(int whichItem){
return mNoteList.get(whichItem);
}
@Override
public long getItemId(int whichItem){
return whichItem;
}
@Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
// check if view has been inflated already
if (view == null){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); // ERROR HERE
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
return view;
}
}
问题出在 getView
方法,我试图膨胀
布局
: Android Studio会抛出错误:'无法解析getSystemService(java.lang.String)'。
The problem is in the getView
method, where I'm attempting to inflate
the layout
: Android Studio throws an error: 'Cannot resolve getSystemService(java.lang.String)'.
完整新手只是通过这本书我不知道从哪里去或者试图解决它 - 有人可以帮忙吗?
As a complete newcomer just following through the book I have no idea where to go from here or what to try to resolve it - can anyone help?
推荐答案
LayoutInflater 的最佳方法是在活动上调用
。这样,活动的主题就被考虑在内了。如果 getLayoutInflater()
NoteAdapter
是在活动
中定义的,只需调用 getLayoutInflater()
。如果 NoteAdapter
在其自己的单独Java类文件中定义,则通过构造函数传入 LayoutInflater
。
The best way to get a LayoutInflater
is by calling getLayoutInflater()
on an Activity
. That way, the activity's theme is taken into account. If NoteAdapter
is defined inside of an Activity
, just call getLayoutInflater()
. If NoteAdapter
is defined in its own separate Java class file, pass in a LayoutInflater
via the constructor.
要更直接地解决您的问题,任何查看
,例如 ListView
,可以调用 getContext()
来获取上下文
。这就是定义 getSystemService()
的地方。因此,用 viewGroup.getContext()替换
将起作用。 getSystemService()
.getSystemService()
To more directly address your question, any View
, like ListView
, can call getContext()
to get a Context
. That is where getSystemService()
is defined. So, replacing getSystemService()
with viewGroup.getContext().getSystemService()
would work.
这篇关于无法解析ListView适配器中的getSystemService方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!