首页 > 技术文章 > 鸿蒙开发基础(四)跨设备运行

cnyl 原文

config.json

"deviceType": ["tv", "wearable"]

MainAbilitySlice

public class MainAbilitySlice extends AbilitySlice {

    private DirectionalLayout myLayout = new DirectionalLayout(this);

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        myLayout.setOrientation(Component.VERTICAL);
        LayoutConfig config = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(255, 255, 255));
        myLayout.setBackground(element);

        Text text = new Text(this);
        text.setLayoutConfig(config);

        if(DeviceInfo.getDeviceType().equals("tv")) {
            // 运行在TV上执行的代码
            text.setText("华为智慧屏");
            text.setTextColor(new Color(0xFFFF0000));
            text.setTextSize(200);
        } else if(DeviceInfo.getDeviceType().equals("wearable")) {
            // 运行在Wearable上执行的代码
            text.setText("华为智能手表");
            text.setTextColor(new Color(0xFF0000FF));
            text.setTextSize(50);
        }
        text.setTextAlignment(TextAlignment.CENTER);
        myLayout.addComponent(text);

        super.setUIContent(myLayout);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

推荐阅读