我的片段中有列表视图,并且我试图在onclick事件中从列表视图中获取项目。但是我收到错误消息,建议我将名单宣布为最终名单。当我尝试声明我的名单到决赛时。我收到另一个错误“不兼容...”。
这是我的代码
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.announcement_fragment, container, false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<Announcement> listAnnouncement = GetlistAnnouncement();
ListView lv = (ListView)rootView.findViewById(R.id.list_announcement);
lv.setAdapter(new AnnouncementAdapter(listAnnouncement, getActivity()));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Announcement item = lv.getItemAtPosition(i);
}
});
return rootView;
}
我在这一行有错误
Announcement item = lv.getItemAtPosition(i);
答:
更改
Announcement item = lv.getItemAtPosition(i);
至
Announcement item = listAnnouncement.get(i);
要么
Announcement item = (Announcement)adapterView.getItemAtPosition(i);
最佳答案
但是我收到错误消息,提示我宣布我的名单为最终名单
您的lv必须是最终的原因,因为它用于匿名内部类中。
Cannot refer to a non-final variable inside an inner class defined in a different method
我收到另一个错误“不兼容...”。
无需使用lv或做final。改变这个
Announcement item = lv.getItemAtPosition(i);
至
Announcement item = (Announcement)adapterView.getItemAtPosition(i);
getItemAtPosition
返回需要强制转换的对象文件:
public Object getItemAtPosition (int position)
Added in API level 1
Gets the data associated with the specified position in the list.
Parameters
position Which data to get
Returns
The data associated with the specified position in the list
关于android - 从 fragment 中的 ListView 获取项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31932798/