【模块-Java 布局】HarmonyOS Codelab挑战赛记录

编程入门 行业动态 更新时间:2024-10-14 08:27:52

工具准备

  • DevEco Studio
  • ComponentCodelab源码
  • SDK下载(可直接在编辑器中直接下载)
  • 实名认证过的华为开发者账号

项目运行

由于手上没有真机,所以直接用虚拟设备进行运行。
点击DevEco studio上面的Tools,然后选择HVD Manager,这时候会跳转到华为开发者网站,这就是为什么需要一个认证过的开发者账号,因为试用p40,需要有账号。





到这一步,我们就把P40已经启动起来了,但是项目还没有运行到P40上,这时候需要将项目运行到P40上,点击Run/Run ‘entry’

然后选择P40,点击OK即可

这时候发现,项目并没有成功的运行,发生了报错!!!

不怕,我们把错误信息去搜索下,参考此博客https://wwwblogs/qixingchao/p/14609384.html

原因在于config文件上的"releaseType": “Beta1”,把此行删除即可

这时候就成功的运行了项目。

体验TabList和Tab组件

创建布局文件

新增页面按钮及事件

效果图

体验ListContainer组件

编写新闻主界面,设置样式,注意,如果粘贴代码发现报错,把缺少的包进行导入,鼠标放在错误,点击 Import class,下面几个java文件同理

编写新闻类别详细布局

编写新闻列表的item的详细布局

构造新闻类别的provider

构造新闻列表的provider

编写ListContainerSlice,继承AbilitySlice,加载布局

ListContainerSlice.java

public class ListContainerSlice extends AbilitySlice {
    private static final float FOCUS_TEXT_SIZE = 1.2f;
    private static final float UNFOCUS_TEXT_SIZE = 1.0f;
    private Text selectText;
    private ListContainer newsListContainer;
    private ListContainer selectorListContainer;
    private List<NewsInfo> totalNews;
    private List<NewsInfo> selectNews;
    private NewsTypeProvider newsTypeProvider;
    private NewsListProvider newsListProvider;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_news_list_layout);
        initView();
        initProvider();
        setListContainer();
        initListener();
    }

    private void initView() {
        selectorListContainer = (ListContainer) findComponentById(ResourceTable.Id_selector_list);
        newsListContainer = (ListContainer) findComponentById(ResourceTable.Id_news_container);
    }

    private void initProvider() {
        String[] listNames = new String[]{"All", "Health", "Finance", "Technology", "Sport", "Internet", "Game"};
        newsTypeProvider = new NewsTypeProvider(listNames, this);
        newsTypeProvider.notifyDataChanged();

        String[] newsTypes = new String[]{"Health", "Finance", "Finance", "Technology", "Sport", "Health", "Internet", "Game", "Game", "Internet"};
        String[] newsTitles = new String[]{
                "Best Enterprise Wi-Fi Network Award of the Wireless Broadband Alliance 2020",
                "Openness and Cooperation Facilitate Industry Upgrade",
                "High-voltage super-fast charging is an inevitable trend",
                "Ten Future Trends of Digital Energy",
                "Ascend Helps Industry, Learning, and Research Promote AI Industry Development in the National AI Contest",
                "Enterprise data centers are moving towards autonomous driving network",
                "One optical fiber lights up a green smart room",
                "Trust technology, embrace openness, and share the world prosperity brought by technology",
                "Intelligent Twins Won the Leading Technology Achievement Award at the 7th World Internet Conference",
                "Maximizing the Value of Wireless Networks and Ushering in the Golden Decade of 5G"
        };
        totalNews = new ArrayList<>();
        selectNews = new ArrayList<>();
        for (int i = 0; i < newsTypes.length; i++) {
            NewsInfo newsInfo = new NewsInfo();
            newsInfo.setTitle(newsTitles[i]);
            newsInfo.setType(newsTypes[i]);
            totalNews.add(newsInfo);
        }
        selectNews.addAll(totalNews);
        newsListProvider = new NewsListProvider(selectNews, this);
        newsListProvider.notifyDataChanged();
    }

    private void  setListContainer() {
        selectorListContainer.setItemProvider(newsTypeProvider);
        newsListContainer.setItemProvider(newsListProvider);
    }

    private void initListener() {
        selectorListContainer.setItemClickedListener((listContainer, component, position, listener) -> {
            setCategorizationFocus(false);
            Component newsTypeText = component.findComponentById(ResourceTable.Id_news_type_text);
            if (newsTypeText instanceof Text) {
                selectText = (Text) newsTypeText;
            }
            setCategorizationFocus(true);
            selectNews.clear();
            if (position == 0) {
                selectNews.addAll(totalNews);
            } else {
                String newsType = selectText.getText();
                for (NewsInfo newsData : totalNews) {
                    if (newsType.equals(newsData.getType())) {
                        selectNews.add(newsData);
                    }
                }
            }
            updateListView();
        });
        selectorListContainer.setSelected(true);
        selectorListContainer.setSelectedItemIndex(0);
    }

    private void setCategorizationFocus(boolean isFocus) {
        if (selectText == null) {
            return;
        }
        if (isFocus) {
            selectText.setTextColor(new Color(Color.getIntColor("#afaafa")));
            selectText.setScaleX(FOCUS_TEXT_SIZE);
            selectText.setScaleY(FOCUS_TEXT_SIZE);
        } else {
            selectText.setTextColor(new Color(Color.getIntColor("#999999")));
            selectText.setScaleX(UNFOCUS_TEXT_SIZE);
            selectText.setScaleY(UNFOCUS_TEXT_SIZE);
        }
    }

    private void updateListView() {
        newsListProvider.notifyDataChanged();
        newsListContainer.invalidate();
        newsListContainer.scrollToCenter(0);
    }
}

进行关联跳转

运行效果

体验RadioContainer组件

编写radio_container布局文件

编写RadioContainerSlice文件,设定背景,初始化组件并增加事件


public class RadioContainerSlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_radio_container);
        initComponent();
    }

    private StateElement getStateElement() {
        ShapeElement elementButtonOn = new ShapeElement();
        elementButtonOn.setRgbColor(RgbPalette.RED);
        elementButtonOn.setShape(ShapeElement.OVAL);

        ShapeElement elementButtonOff = new ShapeElement();
        elementButtonOff.setRgbColor(RgbPalette.DARK_GRAY);
        elementButtonOff.setShape(ShapeElement.OVAL);

        StateElement checkElement = new StateElement();
        checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn);
        checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff);
        return checkElement;
    }

    private void initComponent() {
        Text answer = (Text) findComponentById(ResourceTable.Id_answer);
        RadioContainer container = (RadioContainer)findComponentById(ResourceTable.Id_radio_container);
        int count = container.getChildCount();
        for (int i = 0; i < count; i++) {
            ((RadioButton) container.getComponentAt(i)).setButtonElement(getStateElement());
        }
        container.setMarkChangedListener((radioContainer1, index) -> {
            answer.setText(String.format("[%c]", (char)('A'+index)));
        });
    }
}

运行效果图

体验Checkbox组件

编写checkbox布局文件

编写CheckboxSlice文件,设置checkbox背景以及添加选中事件

在MainAbilitySlice关联跳转

效果展示

体验DatePicker组件

编写data_picker布局文件

编写DatePickerSlice Java文件,初始化组件,绑定事件

跳转页面绑定

public class DatePickerSlice extends AbilitySlice {
    private DatePicker datePicker;
    private Text textDate;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_data_picker);
        initComponent();
        initDate();
        setValueChangedListener();
    }

    //初始化组件
    private void initComponent() {
        datePicker = (DatePicker) findComponentById(ResourceTable.Id_date_pick);
        textDate = (Text) findComponentById(ResourceTable.Id_text_date);
    }

    //显示日期
    private void initDate() {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        textDate.setText(String.format("%02d/%02d/%4d", day, month, year));
    }

    private void setValueChangedListener(){
        datePicker.setValueChangedListener(
                new DatePicker.ValueChangedListener() {
                    @Override
                    public void onValueChanged(DatePicker picker, int year, int monthOfYear, int dayOfMonth) {
                        textDate.setText(String.format("%02d/%02d/%4d", dayOfMonth, monthOfYear, year));
                    }
                }
        );
    }
}

运行效果

体验DirectionalLayout布局

新建布局文件directional_layout

编写DirectionalLayoutSlice Java文件

关联页面跳转绑定

效果展示

体验DependentLayout布局

编写dependent_layout布局文件

编写DependentLayoutSlice Java文件,加载布局配置文件

配置页面跳转

效果展示

体验StackLayout布局

编写布局文件

编写java文件,加载布局

设置关联跳转

效果展示

体验TableLayout布局

编写布局配置文件

编写java文件,配置点击事件

TableLayoutSlice .java文件

public class TableLayoutSlice extends AbilitySlice {
    private Text info;
    private Button call;
    private Button clear;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_table_layout);
        initComponent();
        setClickedListener();
    }

    private void initComponent() {
        info = (Text)findComponentById(ResourceTable.Id_info);
        call = (Button)findComponentById(ResourceTable.Id_call);
        clear = (Button)findComponentById(ResourceTable.Id_clear);
    }

    private void setClickedListener() {
        call.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                String toastInfo = info.getText();
                if (toastInfo == null || toastInfo.isEmpty()) {
                    toastInfo = "Please enter the number!";
                } else {
                    toastInfo = "Call " + info.getText();
                }
                new ToastDialog(getContext())
                        .setText(toastInfo)
                        .setAlignment(LayoutAlignment.CENTER)
                        .setOffset(0,180)
                        .show();
            }
        });

        clear.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                info.setText("");
            }
        });

        TableLayout table = (TableLayout)findComponentById(ResourceTable.Id_table);
        int childNum = table.getChildCount();
        for (int index = 0; index < childNum; index++) {
            Button child = (Button)(table.getComponentAt(index));
            child.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    if (component instanceof Button) {
                        Button button = (Button)component;
                        info.setText(info.getText() + button.getText());
                    }
                }
            });
        }
    }
}

关联跳转

效果图

更多推荐

【模块-Java 布局】HarmonyOS Codelab挑战赛记录

本文发布于:2023-06-13 09:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1373080.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:挑战赛   布局   模块   Java   HarmonyOS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!