白羽
2018-06-15
来源 :网络
阅读 2394
评论 0
摘要:本文将带你了解Android 源码之button高亮效果,希望本文对大家学Android有所帮助。
android默认的button在点击以后有默认的高亮效果,但是默认的button比较丑,要替换成自己的按钮背景,采用的方法是:
button.setBackgroundDrawable(drawable);//or
button.setBackgroundResource(resid);
可是这样就没有了点击以后的高亮效果。要实现高亮的效果,网上采用的是在XML中配置的方法:
<selector xmlns:android="//schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/highlight" />
<item android:drawable="@drawable/normal" /></selector>
以上代码没试过,暂且记录着,以后试过了补完具体怎么弄。
我在实际开发中,无法使用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频道
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号