gpt4 book ai didi

android - 使用 switch case 通过 ListView 从 fragment 打开 Activity 时出错

转载 作者:行者123 更新时间:2023-11-30 00:38:18 26 4
gpt4 key购买 nike

我想通过单击 ListView 从 fragment 中打开 Activity ,但在特定行上出现错误。我在下面提到我查阅了很多文档,但没有一个对我有用。

任何帮助都会很棒。谢谢!

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;}}}

日志:

          java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.bulletin.theinvincible.nautical.ServicesFragment$1.onItemClick(ServicesFragment.java:73)

最佳答案

来自Documentation

Object getItemAtPosition (int position) : Gets the data associated with the specified position in the list.

如果你想根据 ListView 的位置开始新的 Activity 。您可以简单地尝试:

    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;
}
}
});

关于android - 使用 switch case 通过 ListView 从 fragment 打开 Activity 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com