ListView is often used during Android Application Development, and buttons and other controls in each Item need to be monitored for events. When you add an OnClickListener to a Button, you may subconsciously find each button in the getView method of the ListView adapter and assign an OnClickListener to it. However, when there is a large amount of data, the new listeners will inevitably put a certain amount of pressure on the memory, and each Listener has the same function. What you need to know in Listener is, it is the index of the Item where the caller is located. How can we make better use of memory?
Since each Listener has the same function, a Listener can be constructed in singleton mode. As follows:
MyOnClickListener MyOnClickListener instance = (instance == instance = }
However, our requirements do not end with this. In many cases, we also need to know which position button is clicked. We need to make different actions in the Listener according to position.
To understand the attributes of external controls within the Listener, we first think of passing parameters, but because our Listener uses the singleton mode, parameters passed by each button to the Listner must overwrite the parameters passed by the previous button. Therefore, there is only one solution left, that is, the information is obtained through the onClick function parameter (View view. However, the view here should be a Button, and the Button does not have the position information. Naturally, the solution came out: Reload the Button class.
MyButton index = -1 setIndex( .index = MyButton(Context context, AttributeSet attrs, }
Next, we need to change the type of the Button in the item to the custom MyButton in the xml file. Change <Button> </Button> to <your. package. name. myButton> </your. package. name. myButton>, while in the getView function of the adapter, the return value obtained by findViewById () is forcibly converted to MyButton, and its setIndex function is called to set the Index value. At the same time, the overload onClick function in MyOnClickListener converts the view object to the MyButton type, and calls the getIndex function to obtain the position information for corresponding operations.
Adapter:
MyButton button = View getView( View view = (convertView == view = LayoutInflater.from(activity).inflate(R.layout.company_detail_campus_talk_item, button = }
In MyOnClickListener:
index = }
In this way, we implement the business logic of using the same Listener to listen to events for different items in the ListView. To share data between the Adapter and Listener, you can add parameters of the Listener getInstance function and member variables of the Listener class.