How to get the position of toggle button clicked within listview?

两盒软妹~` 提交于 2019-12-12 03:27:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!