布局文件
1. 创建XML布局
entry > src > main > resources > base”,在base文件夹下创建一个目录,命名为“layout”
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:height="match_parent"
ohos:orientation="vertical"
>
<Text
ohos:id="$+id:text"
ohos:width="match_content"
ohos:height="match_content"
ohos:text_size="25vp"/>
<Button
ohos:id="$+id:button"
ohos:width="match_content"
ohos:height="match_content"
/>
</DirectionalLayout>
2. 加载XML布局
在代码中需要加载XML布局,并添加为根布局或作为其他布局的子Component。
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 加载XML布局作为根布局
super.setUIContent(ResourceTable.Layout_test);
}
3. ID
在 DependentLayout 布局中,组件之间需要描述相对位置关系,描述时要通过 ID 来指定对应组件。
布局中的组件通常要设置独立的 ID,以便在程序中查找该组件。如果布局中有不同组件设置了相同的 ID,在通过 ID 查找组件时会返回查找到的第一个组件,因此尽量保证在所要查找的布局中为组件设置独立的 ID 值,避免出现与预期不一样。
定义id
ohos:id="$+id:text"
绑定id事件,这里对button进行绑定,可以通过xml里面实现button的属性,也可以通过java代码来实现
例如button的上文字的大小
Button button = (Button) findComponentById(ResourceTable.text)
button .setTextSize(50);
也可以通过xml文件来设置button的字体大小
ohos:text_size="50"
4.Ability 中使用纯代码绘制布局及 UI 组件代码示例
public class MainAbility extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
//super.setMainRoute(MainAbilitySlice.class.getName());
// 使用代码生成 UI 布局与组件
// 创建线性布局, 传入当前界面 Ability 对象
DirectionalLayout directionalLayout = new DirectionalLayout(this);
// 设置水平方向
directionalLayout.setOrientation(Component.HORIZONTAL);
// 配置上述线性布局
// 创建布局配置对象 , DirectionalLayout.LayoutConfig , 构造函数中传入宽高设置
DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig(
DirectionalLayout.LayoutConfig.MATCH_PARENT,
DirectionalLayout.LayoutConfig.MATCH_PARENT);
// 将布局配置对象设置给布局对象
directionalLayout.setLayoutConfig(layoutConfig);
// 设置布局背景颜色
// 创建背景元素
ShapeElement shapeElement = new ShapeElement();
// 设置绿色
shapeElement.setRgbColor(new RgbColor(0x00, 0xFF, 0x00));
// 将背景设置给布局
directionalLayout.setBackground(shapeElement);
// 创建 Text 文本组件
Text text = new Text(this);
// 创建布局配置对象 , DirectionalLayout.LayoutConfig , 构造函数中传入宽高设置 , 这里设置成 800 x 800
DirectionalLayout.LayoutConfig textLayoutConfig = new DirectionalLayout.LayoutConfig(
800, 800);
// 将布局配置对象设置给布局对象
text.setLayoutConfig(textLayoutConfig);
// 设置组件背景颜色
// 创建背景元素
ShapeElement textShapeElement = new ShapeElement();
// 设置绿色
textShapeElement.setRgbColor(new RgbColor(0xFF, 0xFF, 0xFF));
// 设置给 Text 组件
text.setBackground(textShapeElement);
// 设置文字显示
// 设置文字颜色
text.setTextColor(Color.RED);
// 设置文字大小
text.setTextSize(50);
// 设置显示的文本
text.setText("代码创建的 Text 组件");
// 设置对齐方式 , 居中
text.setTextAlignment(TextAlignment.CENTER);
// 将组件添加到布局中
directionalLayout.addComponent(text);
// Ability 显示上述创建的布局
super.setUIContent(directionalLayout);
}
}
可以看出使用java代码创建一个文本框和设置字体大小以及颜色需要很多代码,所以在设置使用简单的组件样式我是用xml布局里配置,个性化的UI时这时候可以通过自定义控件通过java代码来实现比较好。