在自定义android上从自定义listView获取显示数据的对象

时间:2019-04-10 07:36:46

标签: android listview

我目前正在android studio中创建ListView。然后,通过创建一个存储对象的自定义适配器来填充listView,如下所示:

public class EventAdapter extends ArrayAdapter<AbstractEvent>{
private Context mContext;
private List<AbstractEvent> events = new ArrayList<>();

public EventAdapter(Context context, List<AbstractEvent> events){
    super(context, 0, events);
    mContext = context;
    this.events = events;
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    // Get the data item for this position
    AbstractEvent event = getItem(position);
    // Check if an existing view is being reused, otherwise inflate the view
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.event_listitem_layout, parent, false);
    }
    // Lookup view for data population
    TextView eventName = (TextView) convertView.findViewById(R.id.eventName);
    TextView eventID = (TextView) convertView.findViewById(R.id.eventID);

    eventName.setText(event.getTitle());
    eventID.setText(event.getId());
    // Return the completed view to render on screen
    return convertView;
}

}

然后将其添加到mainActivity类中的列表视图中:

EventAdapter eAdapter = new EventAdapter(this,events) ;
    listView.setAdapter(eAdapter);

这可以在列表视图中正确显示信息,但是当我在列表视图中点击对象时,我希望能够获得该对象(或只是数据字段之一)。我将如何去做?

1 个答案:

答案 0 :(得分:0)

在您的MainActivity中的列表视图上添加一个列表器,例如

listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> a, View view, int position,
                        long id) {

                    AbstractEvent abstracteventObject = (AbstractEvent)adapter.getItem(position);

                }
            });

,您将获得abstracteventObject在您想使用的地方使用它,