这篇文章记录了怎么使用drawable中的StateList来实现自定义标题 以及 按钮,先看一下效果图吧:
先介绍一下drawable中的stateList
先看代码:
send_button.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/btn_pressed" />
<item android:state_focused="true" android:drawable="@drawable/btn_pressed" />
<item android:drawable="@drawable/btn_normal" />
</selector>
这段代码描述的是“发送”按钮,默认情况下,呈现的是btn_normal;当press或者focus的时候,为btn_pressed。两图片如下:
而stateList是一种drawable,所以上面的send_button.xml其实在android应用程序看来就是类似一张图片,不过这张图片是有状态的。 作为按钮,当点击这个控件时,它会提供一个友好的相应。
关于stateList,请参考官方文档:http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
Tips: 定义中的状态的匹配是按照顺序进行的,匹配到第一个成功就不往下匹配了(这里我也不太清楚具体的应用场景,反正就是提醒,定义状态的顺序是比较重要的,也可以把这里的状态类比有着break的switch语句块)。状态的顺序很重要,文章有个例子,参考那个例子就可以了,而对于按钮,运用本文中的例子也可以了。
使用drawable
跟使用图片是一样的,直接上代码:
<Button
android:id="@+id/sendbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...
android:background="@drawable/send_button"
android:text="发 送" />
本文中的例子还有一处使用了stateList,就是标题栏中跳转的导航按钮。
代码如下:
right_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/right_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/right_normal"/>
</selector>
<ImageButton
android:id="@+id/about_us_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...
android:background="@drawable/right_selector"
android:src="@drawable/arrow_left" />
设置无标题
默认情况下,android应用是有标题的,而我们这里定义了标题,就不需要原来的标题了,这里要使用@android:style/Theme.NoTitleBar这个style。我是在activity中设置的,具体看代码:
AndroidManifest.xml
<activity android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
集成layout文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/white">
<include layout="@layout/head"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30sp"
layout="@layout/content" />
</LinearLayout>
源代码位置:http://download.youkuaiyun.com/download/stalendp/4663132