andriod linearlayout 上边框
时间: 2023-09-04 20:02:30 浏览: 60
在 Android 中,要在 LinearLayout 上添加上边框,可以通过两种方式来实现。
第一种方式是在布局的 XML 文件中使用属性来设置上边框。可以通过设置 LinearLayout 的 background 属性为一个具有上边框的 shape,来添加上边框样式。比如可以创建一个 drawable 文件,定义一个带有上边框的 shape,然后将该 drawable 文件设置为 LinearLayout 的 background。
示例代码如下:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border_with_top_line"
...>
<!-- 子视图 -->
</LinearLayout>
```
其中 `border_with_top_line.xml` 是一个定义带有上边框的 shape 的 drawable 文件,示例代码如下:
```xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#000000" />
<padding
android:top="1dp" />
</shape>
```
第二种方式是在代码中动态设置上边框。可以通过 LinearLayout 的 `setPadding()` 方法设置上边框的高度,以及通过 `setBackgroundColor()` 方法设置上边框的颜色。
示例代码如下:
```java
LinearLayout linearLayout = findViewById(R.id.linear_layout);
// 设置上边框的颜色
linearLayout.setBackgroundColor(Color.BLACK);
// 设置上边框的高度
int borderWidth = 1; // 单位为像素
linearLayout.setPadding(0, borderWidth, 0, 0);
```
以上就是在 Android 的 LinearLayout 上添加上边框的两种方式。