需求: 默认的标题栏显示, 图片的背景图为白色, 点击图片, 将其背景色改为黑色, 同时隐藏标题栏, 再次时显示标题栏, 背景色改为白色.
效果如下:
参见: 隐藏TitleBar的方式
实现过程
首先, 创建布局文件
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent">
<!--进入时的背景色为白色, 标题栏可见, 点击之后隐藏标题栏-->
<DirectionalLayout
ohos:id="$+id:tool_bar_dl"
ohos:height="40vp"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:visibility="visible">
<Button
ohos:id="$+id:back_btn"
ohos:height="40vp"
ohos:width="40vp"
ohos:background_element="$graphic:circle_button_element"
ohos:bottom_margin="15vp"
ohos:left_margin="15vp"
ohos:left_padding="15vp"
ohos:right_padding="15vp"
ohos:text="B"
ohos:text_size="15fp"/>
<DirectionalLayout
ohos:height="match_parent"
ohos:width="300vp"
ohos:left_margin="10vp"
ohos:orientation="vertical">
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="2021年8月6日"
ohos:text_size="20fp"/>
<Text
ohos:height="match_content"
ohos:width="match_content"
ohos:text="南京市雨花台区"
ohos:text_size="12fp"/>
</DirectionalLayout>
</DirectionalLayout>
<Image
ohos:id="$+id:detail_image"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="$graphic:white_background_rectangle"
ohos:image_src="$media:icon"
ohos:scale_mode="zoom_center"/>
</DirectionalLayout>
效果图如下:
其次, 在base/graphic
创建白色矩形和黑色矩形的Shape
ps:
不知道该怎么直接设置背景色, 所以采用这种方式…
black_background_rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid ohos:color="$color:black"/>
</shape>
white_background_rectangle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid ohos:color="$color:white"/>
</shape>
最后, 在Java代码中控制标题栏的显示和隐藏
关键代码如下:
@Override
public void onClick(Component component) {
HiLog.error(LABEL_LOG, "onClick", "");
if (mToolBarDirectionLayout.getVisibility() == Component.HIDE) {
HiLog.error(LABEL_LOG, "Component.HIDE", "");
mToolBarDirectionLayout.setVisibility(Component.VISIBLE);
ShapeElement element = new ShapeElement(getContext(),
ResourceTable.Graphic_white_background_rectangle);
mDetailImage.setBackground(element);
} else {
HiLog.error(LABEL_LOG, "Component.VISIBLE", "");
mToolBarDirectionLayout.setVisibility(Component.HIDE);
ShapeElement element = new ShapeElement(getContext(),
ResourceTable.Graphic_black_background_rectangle);
mDetailImage.setBackground(element);
}
}