Search code examples
androidonclicklistenerandroid-listfragment

Set clicklistener for ListFragment


I have a "modell" class which defines the structure and values of my list, called Application. Now in my ListFragment class I am trying to get the title that has been clicked in the listrow. Following the code that I currently have:

Aplication class:

public class Application {
    private String title;
    private long totalDl;
    private String rating;
    private String icon;


    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public long getTotalDl() {
        return totalDl;
    }
    public void setTotalDl(long totalDl) {
        this.totalDl = totalDl;
    }
    public String getRating() {
        return rating;
    }
    public void setRating(String rating) {
        this.rating = rating;
    }
    public String getIcon() {
        return icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;

    }
}

ListFragment class with the clicklistener section:

public class NewUploadsFragment extends ListFragment {

private Application app;
...

@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);
        Toast.makeText(getActivity(),
                "Item " + app.getTitle() + " was clicked", Toast.LENGTH_SHORT)
                .show();

    }
}

But it does not work, I'll get an error. So my question is if anybody knows how I can show the clicked "title" of the listrow 1. with the Application class and 2. without the Application class?

Thanks guys!


Solution

  • You can get the String from the ListRow by using View.

    // listening to single list item on click
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
          //in this example "name" is the item from row you want to display
          TextView ptitle = (TextView) view.findViewById(R.id.name);
          String Title = ptitle.getText().toString();
          Toast.makeText(getActivity(),"Item " + Title + " was clicked", Toast.LENGTH_SHORT).show();
    }
    });
    

    Change the R.id.name to R.id."the view you want to display"