本文出自https://shuwoom.com博客,欢迎访问!
android开发最常用例子整理----(1)自定义按钮实现
一、Activity
MainActivity.java源码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
二、xml布局文件
activity_main.xml源码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_button"/>
</LinearLayout>
三、相关资源
res/drawable/下的文件:
bg_button.xml源码:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_focused="true" android:drawable="@drawable/bg_button_pressed"></item>
<item android:state_pressed="true" android:drawable="@drawable/bg_button_pressed"></item>
<item android:drawable="@drawable/bg_button_normal"></item>
</selector>
补充:这里除了可以设置state_focused、state_pressed状态下的样式外,还可以设置state_checked、state_selected等状态。
bg_button_normal.png:
bg_button_pressed.png:
四、效果截图
(1)自然状态下的按钮:
(2)按压状态下的按钮: