android默认的button在点击以后有默认的高亮效果,但是默认的button比较丑,要替换成自己的按钮背景,采用的方法是:
button.setBackgroundDrawable(drawable);//or
button.setBackgroundResource(resid);
可是这样就没有了点击以后的高亮效果。要实现高亮的效果,网上采用的是在XML中配置的方法:
android:drawable="@drawable/highlight" />
以上代码没试过,暂且记录着,以后试过了补完具体怎么弄。
我在实际开发中,无法使用XML来配置,需要用代码实现点击高亮的效果。网上没找到现成的,找了一下发现有StateListDrawable就是起到这个作用,一句话就是在不同的状态刷不同的drawable。
Button confirmButton = new Button(this);
confirmButton.setPadding(10, 8, 10, 9);
confirmButton.setText("吧啦吧啦吧啦");
confirmButton.setTypeface(Typeface.MONOSPACE);
confirmButton.setTextColor(Color.WHITE);
confirmButton.setTextSize(20f);
confirmButton.setClickable(true);
confirmButton.setEnabled(true);
ShapeDrawable normalView = new ShapeDrawable(new RoundRectangleShape());
ShapeDrawable pressView = new ShapeDrawable(new RoundRectangleShape().setColor(0x805c5c5c));
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressView);
stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, normalView);
confirmButton.setBackgroundDrawable(stateListDrawable);
ViewGroup mainScreen = (ViewGroup) this.getLayoutInflater().inflate(
R.layout.activity_main, null);
mainScreen.addView(confirmButton, new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道