Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 3924

how to access object properties from inside OnItemClickListener

I'm trying to make movie posters gallery, when user click item on gallerry, image title appears.

I used custom ArrayAdapter to link images with grideview

MoviePoster class as follow:

public class MoviePoster {


    String title;
    int image;

    public MoviePoster(int image, String title) {
        this.image = image;
        this.title = title;
    }
    public MoviePoster(){

    }
}

here is MainACtivity and the image list.

public class MainActivityFragment extends Fragment {
    private MovieAdapter movieAdapter;


    MoviePoster[] posters ={
            new MoviePoster(R.drawable.ironman, "ironman"),
            new MoviePoster(R.drawable.jobs, "jobs"),
            new MoviePoster(R.drawable.superman,"superman"),
            new MoviePoster(R.drawable.terminator, "terminator"),
            new MoviePoster(R.drawable.batman, "batman"),
            new MoviePoster(R.drawable.linux, "linux"),
            new MoviePoster(R.drawable.madara, "madara"),

    };


    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView =  inflater.inflate(R.layout.fragment_main, container, false);

        movieAdapter = new MovieAdapter(getActivity(), Arrays.asList(posters));
        GridView gridView = (GridView) rootView.findViewById(R.id.MoviesGrid);
        gridView.setAdapter(movieAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Toast.makeText(getActivity(), "need to show image title here???",Toast.LENGTH_LONG).show();
            }
        });
        return rootView;
    }
}

I just don't Know how to recall image title for each item. can anyone help??

Upvotes: 0

Views: 110

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

how to recall image title for each item

Do it using i parameter of onItemClick method which is position of clicked item in GridView:

public void onItemClick(AdapterView<?> adapterView, View view, 
                                                int i, long l) {
   MoviewPoster poster = posters[i];
   String strTitle=poster. title;
  }

Or we can also do it using getItemAtPosition method as suggested in comments.

Upvotes: 2

Related Questions