我正在使用日历应用程序,基本上是这背后的想法:我在特定日期有一个添加事件的ListView,我想要做的是当我在ListView中点击当天的特定事件时,onClick方法将需要该事件的ID来自数据库,并用它开始新的活动。所以我需要将该ID传递给onClick方法。我发现了类似的问题HERE,但对我的情况不太了解..
我有这个createBookings
方法,它会在每天的循环中进行添加事件并返回当天事件列表。
public List<Booking> createBookings(Date data) {
if(data!=null) {
.....
ArrayList<Booking> events = new ArrayList<>();
if (c.moveToFirst()) {
do {
Integer eventID;
String eventTitle, start_date, start_time, end_date, color;
eventID = c.getInt(0);
eventTitle = c.getString(1);start_time = c.getString(4); color = "•"+c.getString(7);
if(eventTitle.isEmpty())eventTitle="(no title)";
Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data);
events.add(event);
} while (c.moveToNext());
}
return events;
}
我会假设传递eventID
就好了:
Booking event = new Booking(eventID,color+" "+eventTitle+" "+start_time, data);
但是如何在列表视图中调用onClickListener时如何获取它?我设法做的就是选择项目的getText值。
final List<String> mutableBookings = new ArrayList<>();
final ListView bookingsListView = (ListView) findViewById(R.id.bookings_listview);
final ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mutableBookings);
bookingsListView.setAdapter(adapter);
bookingsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> bookingsListView, View view,
int position, long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getApplicationContext()," "+item, Toast.LENGTH_SHORT).show();
}
});
我的预订课程:
public class Booking {
private Integer id;
private String title;
private Date date;
public Booking(Integer id, String title, Date date) {
this.id = id;
this.title = title;
this.date = date;
}
//lets say I had this method here.. would it return the correct event id
//when called in onClickListener above?
public String getBookingId() {
return ""+id;
}
}
答案 0 :(得分:1)
是的,你在模型类中编写的方法将返回被点击对象的id,但为此你需要先获取对象,所以你可以做的是,在你的onItemClick()
方法中获取你的对象如下
Booking booking = mutableBookings.get(position); // This will return you the object.
现在要获取id
,您可以使用下面的方法
String id = booking.getBookingId(); // Now you can use this as per your needs
是的,我建议您在模型类中使用int
而不是Integer
。
答案 1 :(得分:0)
您单击的listView的项目有一个位置,此位置与您传递给适配器的列表数组中的书籍索引相同(mutableBookings),但如果列表第一项的位置值为1,请务必小心那么你应该减去1来获得mutablebookings列表中的索引值