问题
I have a listview that contains alarm times and a toggle button to turn off/on that alarm. When I click the toggle buttons for the specific listview, I would like to set/cancel that specific alarm. But how do I get the position of the listview I clicked on based on the view?
When I click my toggle button on/off it hits this code:
public void enableAlarm(View view) {
// set/cancel alarm manager pending intent
}
I have some information stored for each particular listview item in a Database, but I need the listview position. How can I get the position from the view?
回答1:
I suggest you create a custom ArrayAdapter
class and override the getView()
method. From that method, you have access to the position of the list item from which the toggle was set, and can create a unique OnCheckedChangeListener
for each toggle button, passing it the position of the list.
I'm assuming you already have an XML layout file for whatever is supposed to be held in each ListView item, since you mention an alarm and toggle buttons.
Update:
In order to get the alarm time and send it to the enableAlarm()
method, you need to save it as a final
variable within getView()
so you can access it within the onCheckedChangeListener
. Look at the code I added after getting the ToggleButton.
@override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = getContext().getLayoutInflater();
v = inflater.inflate(R.layout.alarm_item, parent, false);
}
ToggleButton toggle = (ToggleButton) v.findViewById(R.id.alarmToggle);
//get the alarm time
TextView timeView = (TextView) v.findViewById(R.id.theAlarmTextView);
final String alarmTime = timeView.getText();
toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
//modify your enableAlarm method to take in the time as a String
enableAlarm(buttonView, alarmTime);
}
}
});
return v;
}
来源:https://stackoverflow.com/questions/19342291/how-to-get-the-position-of-toggle-button-clicked-within-listview