利用View来实现
这是最简单直接的方法了,也就是说分割线也本身也变成了一个控件,代码如下
<!--分割线-->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#666666"/>
只需要根据实际需求调整左右上下间距、颜色、宽高就可以了。
进一步的思考
上述代码讲述了利用View来实现分割线效果。但是,如果现在一个页面有10个分割线,每个分割线都是一样的,ctrl c + ctrl v虽然可以很快地完成代码,但却不利于修改,就像下面这样。
<MyView0/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#666666"/>
<MyView1/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#666666"/>
<MyView1/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#666666"/>
<MyView2/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#666666"/>
...
可以看到分割线产生了大量重复代码,这是十分不利于更改的。
其实可以将分割线封装到style里面去。首先先在styles.xml文件里添加一个关于分割线的style,代码如下
<style name="style_divide_line">
<item name="android:layout_height">1dp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:background">@color/line_color</item>
<item name="android:layout_marginLeft">10dp"</item>
<item name="android:layout_marginRight">10dp"</item>
</style>
为了方便更改分割线的统一颜色,将background的颜色值放在了colors.xml中,代码如下
<color name="line_color">#666666</color>
完成了上述代码编写,View只需调用style即可,代码如下
<!--封装后的分割线-->
<View style="@style/line"/>
分割线的代码就简洁了很多,需要修改分割线参数时只要改刚才的style就行了,减少了很多的工作量。
再改改styles.xml
<style name="style_divide_line_1">
<item name="android:layout_height">1dp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:background">@color/line_color</item>
<item name="android:layout_marginLeft">10dp"</item>
<item name="android:layout_marginRight">10dp"</item>
</style>
<style name="style_divide_line_2">
<item name="android:layout_height">2dp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:background">@color/line_color</item>
<item name="android:layout_marginLeft">10dp"</item>
<item name="android:layout_marginRight">10dp"</item>
</style>
<style name="style_divide_line_3">
<item name="android:layout_height">3dp</item>
<item name="android:layout_width">match_parent</item>
<item name="android:background">@color/line_color</item>
<item name="android:layout_marginLeft">10dp"</item>
<item name="android:layout_marginRight">10dp"</item>
</style>
这回把分割线的风格分成了三种,细线、普通线和粗线。需要哪个调用哪个就行了。