零基础学鸿蒙编程-UI控件_ListContainer

什么是ListContainer

ListContainer是用于显示列表的UI控件.效果图:


基础用法

  1. 在主布局文件"ability_main.xml"中增加ListContainer
 
  1. 新增一个Provider用于展示列表中每一行内容
  • 布局文件:list_container_item.xml



    

    


java代码:MyProvider.java

import ohos.agp.components.*;

import java.util.List;

public class MyProvider extends BaseItemProvider {
    private final List dataList;

    public MyProvider(List 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;
    }
}
  1. 在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 getData() {
        List 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 | 安卓 | 前端 | 小程序 | 鸿蒙
公众号:花生皮编程

你可能感兴趣的:(零基础学鸿蒙编程-UI控件_ListContainer)