Search code examples
androidandroid-fragmentsandroid-listfragment

How get item ID from ListFragment in android?


In a Class that extend from ListFragment I am using from onListItemClick :

public class Setting_Fragment extends ListFragment{
    @Override
    public void onListItemClick(ListView l, View v, final int position, long id) {
         if (position == 0) {
               ImageView image = (ImageView) v.findViewById(R.id.img_message);
               image.setOnClickListener(new OnClickListener() {

                 @Override
                 public void onClick(View v) {
                    Log.i("log", "here");
                 }
        });
        }
    }
}

I need to get ImageView and change the image but I can't .

I can't see Log.i("log", "here"); .

Notice : I am using from appcompat_v7 .


Solution

  • You're using the wrong argument, which may be your issue.

    Position is the position in the list that is showing. ListViews only display as many entries as is needed to fill the screen - the ones above and below the screen aren't rendered until you scroll to them and move them onto the screen. Position has to do with what is being shown. id has to do with the actual individual id of the row, regardless of which rows are being rendered.

    EDIT:

    In face, the way you're doing this is all screwed up. You're only setting the onClickListener when the row is clicked...which makes no sense. Here is what you do.

    Go into the XML for the row. In the XML for your ImageView, add this line:

    android:onClick="testPrint"
    

    Then in your activity, created a method at the bottom that looks like this:

    public void testPrint(View view) {
        Log.i("log", "here");
    }
    

    This will print the log when you click the ImageView.