什么是ListContainer
ListContainer是用于显示列表的UI控件.效果图:
基础用法
- 在主布局文件"ability_main.xml"中增加
ListContainer
<ListContainer
ohos:id="$+id:list_container"
ohos:height="match_content"
ohos:width="match_parent"
ohos:layout_alignment="center"/>
- 新增一个Provider用于展示列表中每一行内容
- 布局文件:list_container_item.xml
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<Text
ohos:id="$+id:titleText"
ohos:height="match_content"
ohos:width="match_content"
ohos:text_size="30vp"
ohos:layout_alignment="center"/>
<Component
ohos:height="1vp"
ohos:width="match_parent"
ohos:background_element="#E8E8E8"/>
</DirectionalLayout>
java代码:MyProvider.java
import ohos.agp.components.*;
import java.util.List;
public class MyProvider extends BaseItemProvider {
private final List<String> dataList;
public MyProvider(List<String> dataList) {
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList == null ? 0 : dataList.size();
}
@Override
public Object getItem(int i) {
if (dataList != null && i >= 0 && i < dataList.size()) {
return dataList.get(i);
}
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
final Component cpt;
if (component == null) {
cpt = LayoutScatter.getInstance(componentContainer.getContext()).parse(ResourceTable.Layout_list_container_item, null, false);
} else {
cpt = component;
}
String data = this.dataList.get(i);
Text titleText = (Text) cpt.findComponentById(ResourceTable.Id_titleText);
titleText.setText(data);
return cpt;
}
}
- 在Slice中实例化Provider,设置数据,并将provider设置给ListContainer
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
MyProvider myProvider = new MyProvider(getData());
listContainer.setItemProvider(myProvider);
}
private List<String> getData() {
List<String> dataList = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
dataList.add("数据-" + (i));
}
return dataList;
}
}
完整源代码
https://gitee.com/hspbc/harmonyos_demos/tree/master/listContainerDemo
关于我
厦门大学计算机专业 | 前华为工程师
分享编程技术,没啥深度,但看得懂,适合初学者。
Java | 安卓 | 前端 | 小程序 | 鸿蒙
公众号:花生皮编程