Listview setitemonclicklistener没有看到所有项目

时间:2015-06-29 20:03:44

标签: java android listview fragment

我的Fragment上有这个方法,我想进入另一个与我点击的项目不同的活动,但它仅适用于第一个和第二个项目, 这是我的方法:

listView = (ListView) rootView.findViewById(R.id.list);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

   @Override
    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int position, long arg3) {

        int position_from = position;
       Log.i("TRY", Float.toString(position_from));
        Intent intent = new Intent(getActivity(),FbLoginActivity.class);
        startActivity(intent);


    }
});

当我点击第一个&#34; 0.0&#34;当我点击第二个没什么,当我点击第三个&#34; 2.0&#34;而其他人都没有工作。

有时在logcat中我点击其他标签(不是1和3)&#34; unregisterIRListener()被调用&#34;

这是我的所有片段

public class SampleFragment extends Fragment {


    public static String KEY_ID = "id";
    public static String KEY_EMAIL = "email";
    public static String KEY_NAME = "name";
    public static String KEY_JSON = "JSON_DB";

    //EVENTI
    private static final String TAG = SampleActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
    //EVENTI

    private static final String ARG_POSITION = "position";
    private WebView myWebView;

    public ValueCallback<Uri> mUploadMessage;

    private int position;


    public static SampleFragment newInstance(int position) {
        SampleFragment f = new SampleFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);

        return f;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        LoadPreferences();

        Log.i("string", KEY_EMAIL);
        Log.i("string", KEY_ID);
        Log.i("string", KEY_NAME);
        Log.i("string", KEY_JSON);




        position = getArguments().getInt(ARG_POSITION);

        View rootView = inflater.inflate(page, container, false);

        listView = (ListView) rootView.findViewById(R.id.list);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {

                int position_from = position;
               Log.i("TRY", Float.toString(position_from));
                Intent intent = new Intent(getActivity(),FbLoginActivity.class);
                startActivity(intent);


            }
        });


        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(getActivity(), feedItems);
        listView.setAdapter(listAdapter);


        Activity activity = getActivity();
        if (KEY_ID == "0") {

            Toast.makeText(activity, "Non essendo connesso a Facebook non potrai usufruire di tutte le funzionalità che abbiamo creato apposta per te.", Toast.LENGTH_LONG).show();
        }



            switch (position) {
                case 0:

                    Cache cache = App.getInstance().getRequestQueue().getCache();
                    Cache.Entry entry = cache.get(URL_FEED);
                    if (entry != null) {
                        // fetch the data from cache
                        try {
                            String data = new String(entry.data, "UTF-8");
                            try {
                                parseJsonFeed(new JSONObject(data));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    } else {
                        // making fresh volley request and getting json
                        JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET,
                                URL_FEED, null, new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                VolleyLog.d(TAG, "Response: " + response.toString());
                                if (response != null) {
                                    parseJsonFeed(response);
                                }
                            }
                        }, new Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                VolleyLog.d(TAG, "Error: " + error.getMessage());
                            }
                        });

                        // Adding request to volley request queue
                        App.getInstance().addToRequestQueue(jsonReq);
                    }







                    break;
                case 1:



                    break;
                case 2:



                    break;
                case 3:



                    break;

                case 4:

                   break;
            }

       // }



        return rootView;
    }


    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj.getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CallbackManager callbackManager = CallbackManager.Factory.create();
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


        private void LoadPreferences(){
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        KEY_NAME = sharedPreferences.getString("name", "0") ;
        KEY_EMAIL = sharedPreferences.getString("email", "0") ;
        KEY_ID = sharedPreferences.getString("id", "0") ;
        KEY_JSON = sharedPreferences.getString("JSON_DB", "0") ;
        //Toast.makeText(this, name, Toast.LENGTH_LONG).show();
        //Toast.makeText(this, id, Toast.LENGTH_LONG).show();
        //Toast.makeText(this, email, Toast.LENGTH_LONG).show();
    }



}

修改 我的FeedAdapter

public class FeedListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<FeedItem> feedItems;
    ImageLoader imageLoader = App.getInstance().getImageLoader();

    public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
        this.activity = activity;
        this.feedItems = feedItems;
    }

    @Override
    public int getCount() {
        return feedItems.size();
    }

    @Override
    public Object getItem(int location) {
        return feedItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.feed_item, null);

        if (imageLoader == null)
            imageLoader = App.getInstance().getImageLoader();

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView timestamp = (TextView) convertView
                .findViewById(R.id.timestamp);
        TextView statusMsg = (TextView) convertView
                .findViewById(R.id.txtStatusMsg);
        TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
        NetworkImageView profilePic = (NetworkImageView) convertView
                .findViewById(R.id.profilePic);
        FeedImageView feedImageView = (FeedImageView) convertView
                .findViewById(R.id.feedImage1);

        FeedItem item = feedItems.get(position);

        name.setText(item.getName());

        // Converting timestamp into x ago format
        CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
                Long.parseLong(item.getTimeStamp()),
                System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
        timestamp.setText(timeAgo);

        // Chcek for empty status message
        if (!TextUtils.isEmpty(item.getStatus())) {
            statusMsg.setText(item.getStatus());
            statusMsg.setVisibility(View.VISIBLE);
        } else {
            // status is empty, remove from view
            statusMsg.setVisibility(View.GONE);
        }

        // Checking for null feed url
        if (item.getUrl() != null) {
            url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
                    + item.getUrl() + "</a> "));

            // Making url clickable
            url.setMovementMethod(LinkMovementMethod.getInstance());
            url.setVisibility(View.VISIBLE);
        } else {
            // url is null, remove from the view
            url.setVisibility(View.GONE);
        }

        // user profile pic
        profilePic.setImageUrl(item.getProfilePic(), imageLoader);

        // Feed image
        if (item.getImge() != null) {
            feedImageView.setImageUrl(item.getImge(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

        return convertView;
    }

}

1 个答案:

答案 0 :(得分:1)

尝试在适配器类的getView()方法中添加click listner。

       convertView.setOnClickListener(new View.OnClickListener() {                  
                @Override
                public void onClick(View v) {
                  int position_from = position;
                  Log.i("TRY", Float.toString(position_from));
                  Intent intent = new Intent(context,FbLoginActivity.class);
                  context.startActivity(intent);            
                }
            });

也像这样改变构造函数

    private Context context;

    public FeedListAdapter(Context context,Activity activity, List<FeedItem> feedItems) {
        this.context = context;
        this.activity = activity;
        this.feedItems = feedItems;
    }