我想通过单击ListView打开片段中的活动,但我在特定行上收到错误。我在下面提到过 我已经阅读了很多文档,但没有一个对我有用。
任何帮助都会很棒。谢谢!
public class ServicesFragment extends Fragment {
ListView listView;
String[] servicesNameArray;
int[] serviceImages = {
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera,
R.drawable.ic_menu_camera};
public ServicesFragment() {
}
@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.services_fragment, container, false);
Resources resources = getResources();
servicesNameArray = resources.getStringArray(R.array.servicesName);
listView = (ListView) view.findViewById(R.id.listView_services);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
int positionNew = Integer.parseInt(String.valueOf(position));
int pos = (int) adapterView.getItemAtPosition(positionNew);//error in this line
switch (pos) {
case 0:
Intent intent = new Intent(getActivity(), SlipActivity.class);
startActivity(intent);
break;}}});
ServicesAdapter adapter = new ServicesAdapter(this.getActivity(), servicesNameArray, serviceImages);
listView.setAdapter(adapter);
return view;
}
public class ServicesAdapter extends ArrayAdapter<String> {
Context c;
int[] servicesImageArray;
String[] servicesNameArray;
public ServicesAdapter(Context context, String[] servicesNameArray, int[] serviceImages) {
super(context, R.layout.services_layout, R.id.listView_services, servicesNameArray);
Log.d("ashu", "adapter called");
this.c = context;
this.servicesImageArray = serviceImages;
this.servicesNameArray = servicesNameArray;}}}
logcat的:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.bulletin.theinvincible.nautical.ServicesFragment$1.onItemClick(ServicesFragment.java:73)
答案 0 :(得分:1)
Object getItemAtPosition (int position)
:获取与之关联的数据 列表中的指定位置。
如果您想基于listview位置开始新活动。你可以试试:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SlipActivity.class);
startActivity(intent);
break;
}
}
});