天柱山机场到安庆站:Android自定义button的实现,未选中,按下,选中效果

来源:百度文库 编辑:偶看新闻 时间:2024/05/03 09:11:49

  1. package com.test.TestButton;   
  2.   
  3. import android.app.Activity;   
  4. import android.content.Context;   
  5. import android.graphics.drawable.Drawable;   
  6. import android.graphics.drawable.StateListDrawable;   
  7. import android.os.Bundle;   
  8. import android.view.View;   
  9. import android.widget.Button;   
  10.   
  11. public class TestButton extends Activity {   
  12.    @Override  
  13.     public void onCreate(Bundle savedInstanceState) {   
  14.         super.onCreate(savedInstanceState);   
  15.         setContentView(R.layout.main);   
  16.         Integer[] mButtonState = { R.drawable.defaultbutton,   
  17.                 R.drawable.focusedpressed, R.drawable.pressed };   
  18.         Button mButton = (Button) findViewById(R.id.button);   
  19.         MyButton myButton = new MyButton(this);   
  20.         mButton.setBackgroundDrawable(myButton.setbg(mButtonState));   
  21.     }   
  22.   
  23.     class MyButton extends View {   
  24.   
  25.         public MyButton(Context context) {   
  26.             super(context);   
  27.         }   
  28.         //以下这个方法也可以把你的图片数组传过来,以StateListDrawable来设置图片状态,来表现button的各中状态。未选   中,按下,选中效果。   
  29.         public StateListDrawable setbg(Integer[] mImageIds) {   
  30.             StateListDrawable bg = new StateListDrawable();   
  31.             Drawable normal = this.getResources().getDrawable(mImageIds[0]);   
  32.             Drawable selected = this.getResources().getDrawable(mImageIds[1]);   
  33.             Drawable pressed = this.getResources().getDrawable(mImageIds[2]);   
  34.             bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed);   
  35.             bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected);   
  36.             bg.addState(View.ENABLED_STATE_SET, normal);   
  37.             bg.addState(View.FOCUSED_STATE_SET, selected);   
  38.             bg.addState(View.EMPTY_STATE_SET, normal);   
  39.             return bg;   
  40.         }   
  41.     }   
  42. }