情况一:
美工已经把图片给你做好。
这种情况最简单,我们只要在state-container里面指定状态并关联图片即可。
做法:
新建register_state.xml文件,代码如下
<?xml version="1.0" encoding="utf-8"?>
<state-container
xmlns:ohos="http://schemas.huawei.com/res/ohos">
<item ohos:state="component_state_pressed" ohos:element="$media:registerpress"/>
<item ohos:state="component_state_empty" ohos:element="$media:register"/>
</state-container>
ability_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<Button
ohos:height="31.4vp"
ohos:width="85.4vp"
ohos:background_element="$graphic:register_state"
/>
</DirectionalLayout>
运行效果:
情况二:
美工没有把图片给你做好。
这种情况稍显复杂,你可以给美工提出需求。如果人家不鸟咱,咱就要自己写。
做法:
新建register_empty.xml和register_press.xml两个文件
register_empty.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<corners
ohos:radius="15vp"/>
<solid
ohos:color="#21A8FD"/>
</shape>
register_press.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<corners
ohos:radius="15vp"/>
<solid
ohos:color="#0177BE"/>
</shape>
同时修改register_state.xml:
<?xml version="1.0" encoding="utf-8"?>
<state-container
xmlns:ohos="http://schemas.huawei.com/res/ohos">
<item ohos:state="component_state_pressed" ohos:element="$graphic:register_press"/>
<item ohos:state="component_state_empty" ohos:element="$graphic:register_empty"/>
</state-container>
运行效果:
以上我们完成了对按钮的美化效果
同样的,开关美化也类似
ability_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="vertical">
<!--<Button
ohos:height="31.4vp"
ohos:width="85.4vp"
ohos:background_element="$graphic:register_state"
/>-->
<Switch
ohos:height="50vp"
ohos:width="100vp"
ohos:thumb_element="$graphic:register_state"/>
</DirectionalLayout>
修改register_state.xml:
<?xml version="1.0" encoding="utf-8"?>
<state-container
xmlns:ohos="http://schemas.huawei.com/res/ohos">
<!--<item ohos:state="component_state_pressed" ohos:element="$graphic:register_press"/>-->
<item ohos:state="component_state_checked" ohos:element="$graphic:register_press"/>
<item ohos:state="component_state_empty" ohos:element="$graphic:register_empty"/>
</state-container>
运行效果: