4.3【 Harmonyos Development 】 Component ListContainer(Part 1)
Author: Han Ru
Company: Program Ka (Beijing) Technology Co., Ltd
Hongmeng Bus columnist
A ListContainer is a component used to render contiguous, multi-row data that contains a series of list items of the same type.
The design pattern of MVC is: Model: Data: Array... V: View: ListContainer C: Control: Controller Provider
Supported XML attributes
The ListContainer’s common XML attributes are inherited from: Component
The ListContainer’s own XML properties are shown in the following table:
The attribute name | Product description | The values | The values that | Use case |
---|---|---|---|---|
rebound_effect | Enables/disables rebound | Boolean type | You can set true/false directly, or you can refer to a Boolean resource. | ohos:rebound_effect=”true” ohos:rebound_effect=”$boolean:true” |
shader_color | Shader color | Color type | The color value can be set directly, or the color resource can be referenced. | ohos:shader_color=”#A8FFFFFF” ohos:shader_color=”$color:black” |
orientation | Direction of list items | horizontal | Represents a horizontal list. | ohos:orientation=”horizontal” |
vertical | Represents a list of vertical directions. | ohos:orientation=”vertical” |
2. How to use ListContainer
Let’s start with the thought process:
Set data source List, Array, Map, etc. Set data source List, Array, Map, etc. Create a Provider custom class that extends BaseItemProvider and overrides the four necessary methods. Step 6: Add listener OnItemClickListener
1. In the XML layout file:
<? The 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:alignment="center" ohos:orientation="vertical"> <ListContainer ohos:id="$+id:list_container1" ohos:height="200vp" ohos:width="300vp" ohos:background_element="#eeeeee" ohos:layout_alignment="horizontal_center"/> </DirectionalLayout>
2. In the layout directory, create a new layout file for each item: list_item_demo1.xml
<? The XML version = "1.0" encoding = "utf-8"? > <DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_content" ohos:width="match_parent" ohos:left_margin="16vp" ohos:right_margin="16vp" ohos:orientation="vertical"> <Text ohos:id="$+id:item_index" ohos:height="match_content" ohos:width="match_content" ohos:background_element="#33ff00ff" ohos:padding="4vp" ohos:text="Item0" ohos:text_size="20fp" ohos:margin="10vp" ohos:layout_alignment="center"/> </DirectionalLayout>
3, in Java code, com. Example. Hanrulistcontainer directory to create a new package: the provider
This package provides a Java file: ItemDemo. Java,
package com.example.hanrulistcontainer.provider; Public class ItemDemo {private String name; private String name; public ItemDemo(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Each row can contain different data, so you need to adapt different data structures so that they can all be added to the ListContainer.
Create another Java file under the above package: ItemProvider.java, and let it inherit from BaseItemProvider. The methods that must be overridden are as follows:
methods | role |
---|---|
int getCount() | Returns the number of populated table entries. |
Object getItem(int position) | Returns the corresponding data according to position. |
long getItemId(int position) | Returns the id of an item. |
Component getComponent(int position, Component covertComponent,ComponentContainer componentContainer) | Returns the corresponding interface component according to Position. |
Sample code:
package com.example.hanrulistcontainer.provider; import com.example.hanrulistcontainer.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.agp.components.*; import java.util.List; /** * BaseItemProvider * 1. BaseItemProvider ** 2. Override the necessary methods: 4 * getCount()=== Get the total amount of data, that is, the total number to draw. It is generally the length of the data source. * getItem(int position)=== According to position, return the corresponding data. * getItemId(int position)=== According to position, get the id of the item to be drawn, which is position. * getComponent(int position, Component Component, componentContainer, componentContainer) === Position, getComponent(int position, Component Component, componentContainer) === Position, It's just getting the Component. * * * A: First create an XML layout for each item of the Item. * B: Use LayoutScatter to turn the XML layout into Component objects. * C: Get the control on Component: View.findViewById ()-- Control * D: Get the corresponding data in the data source according to position. Then set it to the corresponding control. * E: Returns the Component object. * / / / step1: BaseItemProvider public class ItemProvider extends BaseItemProvider {private List< itemDemo > List; private AbilitySlice slice ; Public ItemProvider(List<ItemDemo> List, abilitySlice slice) {this. List = List; this.slice = slice; } // Step 2: Overwrite the 4 necessary methods /** * getCount(), the number of data sources, the number of items to draw. * * @return usually returns the length of the data source. */ @Override public int getCount() { return list == null? 0: list.size(); ** * @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position ** @Param position */ @override public Object getItem(int position) {if(List! = null && position >= 0 && position < list.size()){ return list.get(position); } return null; } /** * Based on position, Public long getItemId(int position) {return position; } /** ** is used to draw each item. The return value is the drawn Component object. * * @param position The first argument, the position of the item to be drawn. * @Param ConvertComponent second argument, the Component being reused * @Param ComponentContainer third argument, the listContainer itself. * @return */ @Override public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) { final Component cpt; // Convert the XML layout file to a Component object if it does not already have a ConvertComponent object. If (ConvertComponent == null){// From the XML layout corresponding to the current abilitySlice, cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_list_item_demo1,null,false); }else{ cpt = convertComponent; } ItemDemo item=list.get(position); Text = (Text) CPT. FindComponentById (ResourceTable. ID_ITEM_INDEX); text.setText(item.getName()); return cpt; }}
5. In MainabilitySlice. Java, add method, add ListContainer data, and adapt its data structure.
First add a method that provides the data:
Private List< itemDemo > getData(){List< itemDemo > List = new ArrayList<>(); for(int i=0; i<=8; i++){ list.add(new ItemDemo("Item "+i)); } return list; }
Provide a method that initializes the ListContainer and ADAPTS its data structure.
Private void initListContainer(){// 1. Get the ListContainer component in the XML layout ListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container1); List< itemDemo > List = getData(); ItemProvider = new ItemProvider(List, this); ItemProvider = new ItemProvider(List, this); / / 4. To display the contents of a data listContainer. SetItemProvider (itemProvider); }
Then don’t forget to call it in the onStart() method:
@Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); / / call initListContainer (); }
Here we are ready to run:
<img src=”https://img.chengxuka.com/listcontaineryunxing1.gif” alt=”listcontaineryunxing1″ style=”zoom:50%;” />
ListContainer’s common interface
1. Set the response click event.
public interface ItemClickedListener { void onItemClicked(ListContainer container, Component component, int position, long id); ListContainer = ListContainer = ListContainer = ListContainer = ListContainer = ListContainer = ListContainer = ListContainer; The third parameter of the Component of the clicked id item is int position, the position of the clicked item, starting at 0. The fourth parameter is long id, the id of the clicked item, starting at 0
Sample code:
/ / 4. To display the contents of a data listContainer. SetItemProvider (itemProvider); /** * public interface ItemClickedListener {* void onItemClickedListener (listContainer, ClickClicked (Clicked)); /** * public interface ItemClickedListener {* void onItemClicked(listContainer, Clicked(Clicked)); Component component, int position, long id); * * The first parameter: ListContainer * * The second parameter: Component Component, which corresponds to each Item. Component of the ID item being clicked * * Third argument: int position, the position of the item being clicked, starting at 0 * * Fourth argument: Long id, the ID of the item being clicked, Starting from 0 * / listContainer. SetItemClickedListener ((container, the component, the position, id) -> { ItemDemo item = (ItemDemo) listContainer.getItemProvider().getItem(position); New ToastDialog (this). The setText (" you click: "+ item. GetName ()) / / Toast display in the middle of the interface. The setAlignment (LayoutAlignment. CENTER). The show (); });
Response to click event effect:
<img src=”https://img.chengxuka.com/listcontaineryunxing6.gif” alt=”listcontaineryunxing6″ style=”zoom:50%;” />
2. Set the response long press event.
public interface ItemLongClickedListener { boolean onItemLongClicked(ListContainer container, Component component, int position, long id); } : This function returns true, processed. Bind the click event, and long press the true event. Events are not distributed down. False, do not handle. Event distribution is involved.
Set a long-press event for ListContainer in Java:
/** * public interface itemLongClickedListener {* Boolean onItemLongClicked(listContainer container, onItemLongClicked(Clicked)) {/** public interface itemLongClickedListener {* Boolean onItemLongClicked(listContainer container, Component component, int position, long id); *} * The return value of this function: * true, processing. * Bind the click event and press the event * true. Events are not distributed down. * false, does not handle. Event distribution is involved. */ listContainer.setItemLongClickedListener((container, component, position, id) -> { ItemDemo item = (ItemDemo) listContainer.getItemProvider().getItem(position); New ToastDialog (this). The setText (" you long rang: "+ item. GetName ()), setAlignment (LayoutAlignment. CENTER). The show (); return false; });
Response to long press event effect:
<img src=”https://img.chengxuka.com/listcontaineryunxing7.gif” alt=”listcontaineryunxing7″ style=”zoom:50%;” />
ListContainer style setting
The ListContainer stylesheet interface is as follows:
attribute | Java method | role |
---|---|---|
orientation | setOrientation(int orientation) | Setting layout orientation |
– | setContentStartOffSet(int startOffset) setContentEndOffSet(int endOffset) setContentOffSet(int startOffset, int endOffset) |
Sets the start and end offsets for the list container |
rebound_effect | setReboundEffect(boolean enabled) | Sets whether the rebound effect is enabled |
– | setReboundEffectParams(int overscrollPercent, float overscrollRate, int remainVisiblePercent) setReboundEffectParams(ListContainer.ReboundEffectParams reboundEffectParams) |
Set rebound effect parameters |
shader_color | setShaderColor(Color color) | Sets the shader color |
1. Set the listContainer layout orientation: orientation is set to “horizontal”, which means horizontal layout; Orientation is set to “Vertical” for vertical layout. The default is vertical layout.
<ListContainer
...
ohos:orientation="horizontal"/>
Set it in Java code:
listContainer.setOrientation(Component.HORIZONTAL);
The effect is as follows:
<img src=”https://img.chengxuka.com/listcontaineryunxing2.gif” alt=”listcontaineryunxing2″ style=”zoom:50%;” />
Set the start and end offsets of the ListContainer.
ListContainer. SetContentOffSet (200100);
The code in Java:
Private void initListContainer(){// 1. Get the ListContainer component in the XML layout ListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container1); / / set the start and end position offset listContainer. SetContentOffSet (200100); // 2. Instance the data source... }
Set the start offset of the list container to 100 and the end offset to 100.
<img src=”https://img.chengxuka.com/listcontaineryunxing3.gif” alt=”listcontaineryunxing3″ style=”zoom:50%;” />
3. Set the rebound effect.
Set it in XML:
<ListContainer
...
ohos:rebound_effect="true"/>
Set it in Java code:
listContainer.setReboundEffect(true);
Springback effect:
<img src=”https://img.chengxuka.com/listcontaineryunxing4.gif” alt=”listcontaineryunxing4″ style=”zoom:50%;” />
After the rebound effect is turned on, you can adjust the rebound effect by calling the setReboundeffectParams () method.
/* * setReboundEffectParams(int overscrollPercent, float overscrollRate, Int remainVisiblePercent). * / listContainer setReboundEffectParams (40, 0.6 f, 20);
4. Set the shader color.
Set it in XML:
<ListContainer
...
ohos:shader_color="#FFDEAD"/>
Set it in Java code:
listContainer.setShaderColor(new Color(Color.getIntColor("#90EE90")));
Set the shader effect:
<img src=”https://img.chengxuka.com/listcontaineryunxing5.gif” alt=”listcontaineryunxing5″ style=”zoom:50%;” />
Write an example
First take a look at the renderings:
<img src=”https://img.chengxuka.com/listcontaineryunxing8.gif” alt=”listcontaineryunxing8″ style=”zoom:50%;” />
1. First, place 10 small pictures in the media directory:
2. In the layout directory, create a new layout file: list_container_layout.xml
<? The 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"> <ListContainer ohos:id="$+id:list_container2" ohos:height="match_parent" ohos:width="match_parent" ohos:background_element="#eeeeee" ohos:rebound_effect="true" ohos:layout_alignment="horizontal_center"/> </DirectionalLayout>
Here we place a ListContainer, and then we go on to create an XML layout file that represents the layout of each item, list_item_demo2. XML
<? The XML version = "1.0" encoding = "utf-8"? > <DependentLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" ohos:height="match_content" ohos:width="match_parent" ohos:padding="20vp" ohos:margin="10vp" ohos:background_element="#11ff0000" > <Image ohos:id="$+id:image_icon" ohos:height="100vp" ohos:width="100vp" ohos:image_src="$media:icon" ohos:scale_mode="stretch" ohos:vertical_center="true"/> <Text ohos:id="$+id:text_name" ohos:height="match_content" ohos:width="match_content" ohos:text="Name" ohos:text_size="28fp" ohos:text_color="#AA0000" ohos:margin="10vp" ohos:right_of="$id:image_icon" ohos:align_top="$id:image_icon" /> <Text ohos:id="$+id:text_note" ohos:height="match_content" ohos:width="match_content" ohos:text="Note" ohos:text_size="28fp" ohos:margin="10vp" ohos:text_color="#00AA00" ohos:right_of="$id:image_icon" ohos:below="$id:text_name" /> </DependentLayout>
2. Then we create a new provider: listitemprovider.java file under the provider package:
package com.example.hanrulistcontainer.provider; import com.example.hanrulistcontainer.ResourceTable; import ohos.aafwk.ability.AbilitySlice; import ohos.agp.components.*; import java.util.List; import java.util.Map; public class ListItemProvider extends BaseItemProvider{ private List<Map<String,Object>> list; private AbilitySlice slice; public ListItemProvider(List<Map<String, Object>> list, AbilitySlice slice) { this.list = list; this.slice = slice; } @Override public int getCount() { return list == null? 0: list.size(); } @Override public Object getItem(int position) {if(List! = null && position >= 0 && position < list.size()){ return list.get(position); } return null; } @Override public long getItemId(int position) { return position; } @Override public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) { final Component cpt; // Convert the XML layout file to a Component object if it does not already have a ConvertComponent object. If (ConvertComponent == null){// From the XML layout corresponding to the current abilitySlice, cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_list_item_demo2,null,false); }else{ cpt = convertComponent; } Map<String,Object> map =list.get(position); Text TextName = (Text) CPT. FindComponentById (ResourceTable. ID_Text_Name); Text textNote = (Text) cpt.findComponentById(ResourceTable.Id_text_note); Image image =(Image) cpt.findComponentById(ResourceTable.Id_image_icon); textName.setText((String)map.get("name")); textNote.setText((String)map.get("note")); image.setPixelMap((int)map.get("image")); return cpt; }}
3, slice package under a new abilitySlice file: secondabilitySlice. Java
package com.example.hanrulistcontainer.slice; import com.example.hanrulistcontainer.ResourceTable; import com.example.hanrulistcontainer.provider.ListItemProvider; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.ListContainer; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.ToastDialog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class SecondAbilitySlice extends AbilitySlice{ @Override protected void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_list_container_layout); initListContainer(); } private void initListContainer(){// 1. Get the ListContainer component in the XML layout ListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container2); // 2. List<Map<String,Object>> List = getData(); ListItemProvider = new ListItemProvider(List,this); ListItemProvider(List,this); / / 4. To display the contents of a data listContainer. SetItemProvider (listItemProvider); / / 5. Set the click event of each Item. ListContainer setItemClickedListener (container, the component, the position, id) -> { Map<String,Object> item = (Map<String,Object>) listContainer.getItemProvider().getItem(position); New ToastDialog(this).setText(" You clicked :" + item.get("name")+", "+ item. Get (" note")) / / Toast display in the middle of the interface. The setAlignment (LayoutAlignment. CENTER). The show (); }); } private List<Map<String,Object BB0 > GetData (){List<Map<String,Object BB2 BB3 List = new ArrayList<>(); / / icon icon int [] images = {ResourceTable. Media_image_info1, ResourceTable Media_image_info2, ResourceTable.Media_image_info3,ResourceTable.Media_image_info4, ResourceTable.Media_image_info5,ResourceTable.Media_image_info6, ResourceTable.Media_image_info7,ResourceTable.Media_image_info8, ResourceTable.Media_image_info9,ResourceTable.Media_image_info10}; String [] names = {" cao cao ", "liu", "guan yu", "zhuge liang," "Joe", "the sable cicada", "lu", "zhaoyun", "huang gai", "zhou yu"}; Lean String [] notes = {" generation ", "selling straw sandals," "god of wealth", "Mr Wolong", "zhou yu's daughter-in-law," "four magnesium aluminum", "just one", "ever-victorious generals", "willing to beat," "willing to hit persons"}; list= new ArrayList<Map<String,Object>>(); for(int i=0; i<images.length; i++){ Map<String, Object> map = new HashMap<String, Object>(); map.put("image", images[i]); map.put("name", names[i]); map.put("note", notes[i]); list.add(map); } return list; }}
I don’t want to go through the same idea as I did before. However, I changed the type of the data source. I used the custom ItemDemo class when I explained the principle before, but I directly used Map here.
4, modify the program entry:
public class MainAbility extends Ability { @Override public void onStart(Intent intent) { super.onStart(intent); // super.setMainRoute(MainAbilitySlice.class.getName()); super.setMainRoute(SecondAbilitySlice.class.getName()); }}
And then you run it.
More:
1, community: https://www.harmonybus.net/ HongMeng bus
2. Official Account: Harmonybus
3, technical exchange QQ group: 714518656
Lesson 4, video: https://www.chengxuka.com