0

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?

user10297
  • 139
  • 4
  • 11

1 Answers1

2

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;
}
Pat Needham
  • 5,698
  • 7
  • 43
  • 63
  • If I am using the on/off toggle to enable or disable the alarm, is it okay to create a datasource inside the adapter to get the alarm date/time? – user10297 Oct 25 '13 at 01:56
  • It seems that the inflation of the layout is causing the textview to disappear in my listview. Is there a way around this? – user10297 Nov 13 '13 at 05:22
  • The textView within each individual list item, or the TextView above your ListView? You might have to change some `fill_parent` or `match_parent` values to `wrap_content` – Pat Needham Nov 14 '13 at 18:36