1. When there is a button in the ListView often encounter many problems, a more common problem is:
Assumption: There are n item in the ListView when you click the button in one of the item, you need to change the state of the current button, and the state of the button of the last item is changed after you click it, regardless of which button is the last
The state of the button in item has been changed, which involves the problem of the ListView redraw.
The way to solve the above problem is to put a click on the listener event to be encapsulated, in order to solve the above problem.
Give a sample code:
In the GetView method of custom adapter for the ListView:
Mianactivity in Custom Adapter
1 @Override2 PublicView GetView (intposition, View Convertview, ViewGroup parent) {3 4System.out.println ("Getviewgetviewgetviewgetviewgetview");5 if(Convertview = =NULL) {6Viewholder =NewViewholder ();7Convertview =Layoutinflater.from (context). Inflate (8R.layout.item,NULL);9Viewholder.left =(Button) ConvertviewTen . Findviewbyid (r.id.btn_left); OneViewholder.right =(Button) Convertview A . Findviewbyid (r.id.btn_right); -Monclicklistener =myonclicklistener.instance (); -Monclicklistener.setcontext (mainactivity. This); the ViewHolder.left.setOnClickListener (monclicklistener); - Convertview.settag (viewholder); -}Else { -Viewholder =(Viewholder) Convertview.gettag (); + } - + returnConvertview; A}
Viewholder.left This button's Click event Wrapper to eliminate the problem.
Myonclicklistenter:
1 Public classMyonclicklistenerImplementsOnclicklistener {2 3 Private StaticMyonclicklistener Monclicklistener;4 5 PrivateButton btn;6 7 Privatecontext context;8 9 Public StaticMyonclicklistener Instance () {Ten if(Monclicklistener = =NULL) { OneMonclicklistener =NewMyonclicklistener (); A } - - returnMonclicklistener; the } - - Public voidSetContext (Context context) { - This. Context =context; + - } + A @Override at Public voidOnClick (View v) { -BTN =(Button) v; - FinalEditText Edtextview =NewEditText (context); - NewAlertdialog.builder (context). Settitle ("Please enter password"). Setview (Edtextview) -. Setpositivebutton ("OK",NewAlertdialog.onclicklistener () { - in @Override - Public voidOnClick (Dialoginterface Dialog,intwhich) { to System.out +. println ("Setpositivebuttonsetpositivebuttonsetpositivebutton"); -String Passwaord =Edtextview.gettext (). toString () the . Trim (); *System.out.println ("Gets the password is how many-->>" +Passwaord); $ if(Passwaord.equals ("123")) {Panax Notoginseng System.out -. println ("performed 123132123132123132132131313"); theBtn.settext ("Off"); + Btn.setbackgroundresource (r.drawable.toggle_bg_on); A } the + } - }). Create (). Show (); $ $ } - -}
Sample code Download
The item in the Android ListView has a button when you click exception Handling