First define a method to get the Statelistdrawable object:
PrivateStatelistdrawable addstatedrawable (Context context,intIdnormal,intIdpressed,intidfocused) {statelistdrawable SD=Newstatelistdrawable (); drawable Normal= Idnormal = =-1?NULL: Context.getresources (). getdrawable (Idnormal); Drawable pressed= Idpressed = =-1?NULL: Context.getresources (). getdrawable (idpressed); Drawable Focus= Idfocused = =-1?NULL: Context.getresources (). getdrawable (idfocused); //Note the order of the place, as long as a state matches it, the background will be replaced//so don't put a wide range in front, if Sd.addstate (New[]{},normal) in the first words, there is no effectSd.addstate (New int[]{android. R.attr.state_enabled, Android. r.attr.state_focused}, focus); Sd.addstate (New int[]{android. R.attr.state_pressed, Android. r.attr.state_enabled}, pressed); Sd.addstate (New int[]{android. r.attr.state_focused}, focus); Sd.addstate (New int[]{android. r.attr.state_pressed}, pressed); Sd.addstate (New int[]{android. R.attr.state_enabled}, Normal); Sd.addstate (New int[]{}, Normal); returnSD;}
The order in which the comments are made is addState
important.
UseddStateDrawable
// ... The statement before the button is omitted okbtn.setbackgrounddrawable (addstatedrawable(This, R.drawable.btn_normal, r.drawable.btn_selected, r.drawable.btn_selected)); Cancelbtn.setbackgrounddrawable (addStateDrawable ( this, R.drawable.btn_normal, r.drawable.btn_selected, r.drawable.btn_selected));
//bitmap conversion into drawable Publicdrawable bitmap2drawable (Bitmap Bitmap) {bitmapdrawable bd=Newbitmapdrawable (Getresources (), bitmap); Drawable D=(drawable) BD; returnD; } Privatestatelistdrawable addstatedrawable (Bitmap idnormal, Bitmap idpressed, Bitmap idfocused) {statelistdrawable SD =Newstatelistdrawable (); drawable Normal=bitmap2drawable (Idnormal); Drawable pressed=bitmap2drawable (idpressed); Drawable Focus=bitmap2drawable (idfocused); //Note the order of the place, as long as a state matches it, the background will be replaced//so don't put a wide range in front, if Sd.addstate (New[]{},normal) in the first words, there is no effectSd.addstate (New int[]{android. R.attr.state_enabled, Android. r.attr.state_focused}, focus); Sd.addstate (New int[]{android. R.attr.state_pressed, Android. r.attr.state_enabled}, pressed); Sd.addstate (New int[]{android. r.attr.state_focused}, focus); Sd.addstate (New int[]{android. r.attr.state_pressed}, pressed); Sd.addstate (New int[]{android. R.attr.state_enabled}, Normal); Sd.addstate (New int[]{}, Normal); returnSD; }
Application of selector-statelistdrawable in Java code to implement Android background selection