我的片段中有listview,我想在我的onclick事件中从listview中获取项目。但我得到错误,表明我宣布我的名单为最终。当我尝试将我的列表声明为final。我得到另一个错误“不兼容......”。
这是我的代码
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);
答案 0 :(得分:1)
但我得到的错误表明我宣布我的名单为最终
你的lv需要是最终的,因为它在一个匿名的内部类中使用。
Cannot refer to a non-final variable inside an inner class defined in a different method
我收到另一个错误“不兼容......”。
无需使用lv或进行最终决定。改变这个
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