Button 自定义图片,代码绘制样式,添加音效的方法
Button自己在xml文件中绑定监听器
<!-- 设定onclick属性,然后在activity中定义相应的方法 --> <!-- 通过xml布局中通过button的android:onClick属性指定一个方法, 以替代在activity中为button设置OnClickListener。 --> <Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button自己绑定点击事件" android:layout_marginTop="16dp" android:onClick="buttonListener"/>
代码中写一个方法:
/**当用户点击按钮时,Android系统调用buttonListener(View)方法。 * 为了正确执行,这个方法必须是public并且仅接受一个View类型的参数 * @param v button传过来的view对象 * 需要注意的是这个方法必须符合三个条件: 1.public 2.返回void 3.只有一个参数View,这个View就是被点击的这个控件。 */ public void buttonListener(View v){ switch (v.getId()) { case R.id.my_button_id: Toast.makeText(getApplicationContext(), "button自己绑定一个触发函数", 0).show(); break; default: break; } }
自定义点击,按下的样式
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:background="@drawable/button_selector" android:text="自定义按钮样式" />button_selector.xml
用代码来设定按钮的图片样式
<Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="16dp" android:text="用代码动态设定点击样式" />
activity中里:Button styleBt = (Button)findViewById(R.id.style_button_id); styleBt.setBackgroundColor(Color.parseColor("#b9e3d9")); styleBt.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO 自动生成的方法存根 if(event.getAction()==MotionEvent.ACTION_DOWN){ //v.setBackgroundResource(R.drawable.bar_color); v.setBackgroundColor(Color.WHITE); } else if(event.getAction()==MotionEvent.ACTION_UP){ v.setBackgroundColor(Color.parseColor("#b9e3d9")); } return false; } });
用shape画按钮<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/shape" android:layout_marginTop="16dp" android:text="用shape画的圆角按钮" />
shape.xml
用style来设定样式<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@drawable/style_selector" android:layout_marginTop="16dp" android:text="用selector设计的按钮样式" />style_selector.xml
有音效的按钮<Button android: android:layout_gravity="center" android:layout_marginTop="16dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="有音效的按钮" />activity中写:
private SoundPool sp;//声明一个SoundPool private int music;//定义一个整型用load();来设置suondIDsp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量 music = sp.load(this, R.raw.click,1); //把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级 Button musicBt = (Button)findViewById(R.id.music_button_id); musicBt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub sp.play(music, 1, 1, 0, 0, 1); } });
源码下载:http://download.csdn.net/detail/shark0017/7592855