分享

Android自定义button的实现,未选中,按下,选中效果

 nedvedno1 2011-02-24

  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. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多