Данный проект является результатом переноса и разработки проекта AStickyHeader с открытым исходным кодом на HarmonyOS. Исходный проект можно отследить по тегам и адресу GitHub (https://github.com/DWorkS/AStickyHeader).
Изображения:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.har'])
}
Здесь в качестве примера используется PinnedSectionListView.
// Определяем список с закреплённым заголовком
private PinnedSectionListViewWrapper list;
// Пользовательский поставщик элементов содержимого
private ImageAdapter mAdapter;
// Определяем заголовок списка
private List<SimpleSectionedListAdapter.Section> sections = new ArrayList<>();
// Идентификатор ресурса изображения
private Integer[] mImageIds = {
ResourceTable.Media_cat1, ResourceTable.Media_cat2,
ResourceTable.Media_cat3, ResourceTable.Media_cat4,
ResourceTable.Media_cat5, ...,
ResourceTable.Media_cat95, ResourceTable.Media_cat96,
ResourceTable.Media_cat97, ResourceTable.Media_cat98,
ResourceTable.Media_cat99, ResourceTable.Media_cat100,
};
// Имя заголовка
private String[] mHeaderNames = { "Cute Cats", "Few Cats", "Some Cats", "Some More Cats", "Some More More Cats", "Many Cats", "Many Many Cats", "So Many Cats" };
// Позиция заголовка
private Integer[] mHeaderPositions = { 0, 6, 11, 37, 38, 60, 77, 89 };
PinnedSectionGridView аналогичен. Необходимо заменить PinnedSectionListViewWrapper на PinnedSectionGridView и List<SimpleSectionedListAdapter.Section> на List<SimpleSectionedGridAdapter.Section>.
private class ImageAdapter extends BaseItemProvider{
private LayoutScatter mScatter;
public ImageAdapter(Context context) {
mScatter = LayoutScatter.getInstance(context);
}
@Override
public int getCount() {
return mImageIds.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public Component getComponent(int i, Component component, ComponentContainer parent) {
// Связываем изображение и текст с компонентом
Image image;
Text name;
if (component == null) {
component = mScatter.parse(ResourceTable.Layout_list_item, parent, false);
}
image = (Image) component.findComponentById(ResourceTable.Id_img_listItem_image);
image.setPixelMap(mImageIds[i]);
name = (Text) component.findComponentById(ResourceTable.Id_tx_listItem_text);
name.setText("A Cute Cat"+(i+1));
return component;
}
}
PinnedSectionGridView реализует поставщика содержимого списка аналогично PinnedSectionListView.
<!-- PinnedSectionListViewWrapper -->
<com.huawei.astickyheader.lib.ui.PinnedSectionListViewWrapper
ohos:id="$+id:lc_list_list"
ohos:height="match_parent"
ohos:width="match_parent"/>
<!-- 如需侧边导航栏需要增加下面的参数-->
<!-- app:section_index="true"-->
</DirectionalLayout>
<!-- PinnedSectionGridView -->
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
xmlns:app="http://schemas.huawei.com/res/ohos-auto"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<ScrollView
ohos:height="match_parent"
ohos:width="match_parent">
<!-- vertical_spacing 和 horizontal_spacing-->
<!-- 是两个自定义参数,分别用于指定网格布局中的 垂直间距 和 水平间距-->
<com.huawei.astickyheader.lib.ui.PinnedSectionGridView
ohos:id="$+id:tl_grid_grid"
ohos:height="match_content"
ohos:width="match_parent"
ohos:left_margin="10vp"
ohos:right_margin="10vp"
app:vertical_spacing="4vp"
app:horizontal_spacing="4vp"
ohos:column_count="4"/>
</ScrollView>
</DirectionalLayout>
内容项布局:list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:width="match_parent"
ohos:orientation="horizontal"
ohos:height="65vp"
ohos:left_padding="10vp"
ohos:right_padding="10vp">
<Image
ohos:id="$+id:img_listItem_image"
ohos:width="65vp"
ohos:height="65vp"
ohos:scale_mode="clip_center"
ohos:image_src="$media:empty_photo" />
<Text
ohos:id="$+id:tx_listItem_text"
ohos:width="match_content"
ohos:height="match_content"
ohos:layout_alignment="vertical_center"
ohos:text="A Cute Cat"
ohos:text_size="60px"
ohos:margin="10vp"
ohos:text_color="#000000"/>
</DirectionalLayout>
标题布局:list_item_header.xml
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="30vp"
ohos:width="match_parent"
ohos:orientation="vertical"
ohos:left_padding="10vp">
<Text
ohos:id="$+id:tx_listItemHeader_header"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:text_size="15fp"
ohos:background_element="$ohos:color:id_color_background"
ohos:text_alignment="vertical_center"/>
</DirectionalLayout>
3.2 代码中使用布局并初始化
Список SimpleSectionedListAdapter используется для реализации списка с заголовками.
/**
* SimpleSectionedListAdapter 使用方法(需要自定义单项的 BaseItemProvider 或 直接使用 SimpleAdapter)
* mAdapter 为实现 内容项 的 itemProvider
* mHeaderPositions 为 需要添加置顶标题栏 的位置(内容项的坐标之前,从0开始)
* mHeaderNames 为 需要添加置顶标题栏 的文字内容
* 实例化 SimpleSectionedListAdapter,传入 标题栏的 layoutId 和 标题栏中Text组件的 textId
* 将刚刚设置好的 sections 传入
* 最后使用 setItemProvider 方法把 SimpleSectionedListAdapter 填入即可
*/
lc_list_list = (PinnedSectionListViewWrapper) findComponentById(ResourceTable.Id_lc_list_list);
//使用 ImageAdapter 作为 BaseItemProvider
mAdapter = new ImageAdapter(this);
//根据规定的 标题栏位置 创建 sections
for(int i = 0; i < mHeaderPositions.length; i++) {tions.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
}
//初始化 simpleSectionedListAdapter
SimpleSectionedListAdapter simpleSectionedListAdapter = new SimpleSectionedListAdapter(this, mAdapter,
ResourceTable.Layout_list_item_header, ResourceTable.Id_tx_listItemHeader_header);
//设置sections
simpleSectionedListAdapter.setSections(sections.toArray(new Section[0]));
//设置adapter
lc_list_list.setItemProvider(simpleSectionedListAdapter);
``` ```
tl_grid_grid = (GridView) findComponentById(ResourceTable.Id_tl_grid_grid);
//使用 ImageAdapter 作为 BaseItemProvider
mAdapter = new ImageAdapter(this);
//根据规定的 标题栏位置 创建 sections
for (int i = 0; i < mHeaderPositions.length; i++) {
sections.add(new Section(mHeaderPositions[i], mHeaderNames[i]));
}
//初始化 simpleSectionedGridAdapter
SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(this, mAdapter,
ResourceTable.Layout_grid_item_header, ResourceTable.Id_dl_gridItemHeader, ResourceTable.Id_tx_gridItemHeader_header);
//绑定GridView
simpleSectionedGridAdapter.setGridView(tl_grid_grid);
//设置sections
simpleSectionedGridAdapter.setSections(sections.toArray(new Section[0]));
//设置adapter
tl_grid_grid.setItemProvider(simpleSectionedGridAdapter);
v0.2.0-alpha
AS tickyHeader_ohos прошёл через лицензию Apache License, version 2.0.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )