上一节我们了解了PositionLayout(确切位置布局,我更倾向于称为绝对布局),虽然应用场景稀少、维护不方便,但是该有的示例还是不能少。
1UI图拆解及代码实现这个界面我们是不是很熟悉,打开浏览器,很多网站登录界面就是如此,一个用户账号输入框、一个密码输入框,及一个登录按钮,最多再来一个验证码输入框。
作为开发者,很多时候我们拿到的就是这样一张上面标注很多参数的UI图,而我们需要以代码的方式将其实现在用户可操作的界面上。
我们将以PositionLayout布局实现上面的UI图。
① 以PositionLayout为父组件,宽高占满整个屏幕。
② 接下来先进行组件占位,两个TextField和一个Button组件。
③ 根据UI图的比例,让组件左上角(x/y)为起始点,相对父组件的距离进行移动。
④ 优化组件样式。
<PositionLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_parent" ohos:width="match_parent" ohos:background_element="$media:background_login"> <TextField ohos:id="$+id:username" ohos:height="match_content" ohos:width="200vp" ohos:text="请输入用户名..." ohos:background_element="#EAEDED" ohos:text_color="#CCCCCC" ohos:text_size="18fp" ohos:padding="10vp"/>PositionLayout>
我们发现运行后文本框置于整个布局的左上角,并没有到达我们想要的位置,是因为我们没有给其绝对位置的定位。我们在MainAbilitySlice中根据ID找到我们的文本框,然后给其绝对位置X/Y轴距离。效果如图所示。
TextField username = (TextField) findComponentById(ResourceTable.Id_username); username.setContentPosition(1110, 380);
另外两个组件和第一个文件组件一样,找到绝对位置即可实现。
<?xml version="1.0" encoding="utf-8"?><PositionLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_parent" ohos:width="match_parent" ohos:background_element="$media:background_login"> <TextField ohos:id="$+id:username" ohos:height="match_content" ohos:width="200vp" ohos:text="请输入用户名..." ohos:background_element="#EAEDED" ohos:text_color="#CCCCCC" ohos:text_size="18fp" ohos:padding="10vp"/> <TextField ohos:id="$+id:password" ohos:height="match_content" ohos:width="200vp" ohos:text="请输入密码..." ohos:background_element="#EAEDED" ohos:text_color="#CCCCCC" ohos:text_size="18fp" ohos:padding="10vp"/> <Button ohos:id="$+id:login_btn" ohos:height="match_content" ohos:width="200vp" ohos:text="登录" ohos:text_size="20fp" ohos:padding="10vp" ohos:text_color="#FFFFFF" ohos:background_element="#0EAB8D"/>PositionLayout>
TextField username = (TextField) findComponentById(ResourceTable.Id_username);username.setContentPosition(1110, 380);TextField password = (TextField) findComponentById(ResourceTable.Id_password);password.setContentPosition(1110, 522);Button loginBtn = (Button) findComponentById(ResourceTable.Id_login_btn);loginBtn.setContentPosition(1110, 675);
至此,我们就完成了绝对布局中组件的绝对定位,但我不建议你在项目中使用该布局,因为如果设备分辨率发生变化,那么你的布局整个会出现错乱。