以下是一个简单的示例代码,演示如何使用 ListContainer.ItemSelectedListener:
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import java.util.Arrays;
public class MyAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
// 创建一个列表容器
ListContainer listContainer = new ListContainer(this);
listContainer.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
listContainer.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
// 设置适配器
MyListAdapter myListAdapter = new MyListAdapter(Arrays.asList("Item 1", "Item 2", "Item 3"));
listContainer.setItemProvider(myListAdapter);
// 添加项选中监听器
listContainer.setItemSelectedListener(new MyItemSelectedListener());
// 在界面上添加列表容器
super.setUIContent(listContainer);
}
// 自定义的项选中监听器类
private class MyItemSelectedListener implements ListContainer.ItemSelectedListener {
@Override
public void onItemSelected(ListContainer listContainer, Component component, int position, long id) {
// 处理项选中事件的逻辑
showToast("Item Selected: " + position);
}
private void showToast(String message) {
new ToastDialog(getContext())
.setText(message)
.setAlignment(LayoutAlignment.CENTER)
.show();
}
}
// 适配器类
private static class MyListAdapter extends BaseItemProvider {
private final List<String> dataList;
MyListAdapter(List<String> dataList) {
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
// 创建或复用列表项组件
Text text = new Text(componentContainer.getContext());
text.setText(dataList.get(position));
text.setTextSize(50);
text.setPadding(50, 50, 50, 50);
return text;
}
}
}
在这个示例中,MyItemSelectedListener 中的 onItemSelected 方法将在用户选择列表中的项时被调用。您可以在这个方法中处理项选中事件的逻辑。
转载请注明出处:http://www.zyzy.cn/article/detail/2930/鸿蒙OS