有问题实现setOnClickListener - Fragment

时间:2015-06-14 15:21:06

标签: android android-fragments android-listview

我在列表中的项目上执行onclick时遇到问题。错误如下:

06-14 16:15:43.861  11651-11651/wk.gon250.dublinbike E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: wk.gon250.dublinbike, PID: 11651
    java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
            at android.widget.AdapterView.setOnClickListener(AdapterView.java:778)
            at tab.Tab2.onCreateView(Tab2.java:67)

我班的代码是:

公共类Tab2扩展了Fragment {     静态ListView listView;     static CustomAdapter适配器;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tab_2, container, false);
    String Url = "http://mypath";
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "Please, Wait", "Loading..");

    listView = (ListView) v.findViewById(R.id.listViewT_stations);

    JsonObjectRequest req = new JsonObjectRequest(Url, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                Gson gson = new Gson();
                JSONObject jsonNetwork = new JSONObject(response.getString("network"));
                JSONArray stationsArray = jsonNetwork.getJSONArray("stations");
                StationJson[] stations = gson.fromJson(stationsArray.toString(), StationJson[].class);
                adapter = new CustomAdapter(getActivity(), stations, R.layout.station_item);
                listView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            progressDialog.cancel();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Manage Error
            progressDialog.cancel();
        }
    });
    queue.add(req);
    listView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
    return v;
} }

我不能使用listFragment,所以任何消化?如何对我打开新视图的项目实施onclick?什么是最佳做法?

谢谢!

1 个答案:

答案 0 :(得分:2)

错误消息显示:

Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

OnClickListener适用于整个视图的点击事件。在AdapterView中,您通常希望分别为每个项目注册点击事件。为此,您需要使用OnItemClickListener