一种为 Linux ARM 设备构建跨平台 UI 的新方法
UI

> 
> AndroidXML 和 TotalCross 的运用为树莓派和其他设备创建 UI 提供了更简单的方法。
> 
> 
> 


![](/data/attachment/album/202102/18/123715oomfuuz94ioi41ii.jpg "Digital images of a computer desktop")


为应用程序创建良好的用户体验（UX）是一项艰巨的任务，尤其是在开发嵌入式应用程序时。今天，有两种图形用户界面（GUI）工具通常用于开发嵌入式软件：它们要么涉及复杂的技术，要么非常昂贵。


然而，我们已经创建了一个概念验证（PoC），它提供了一种新的方法来使用现有的、成熟的工具为运行在桌面、移动、嵌入式设备和低功耗 ARM 设备上的应用程序构建用户界面（UI）。我们的方法是使用 Android Studio 绘制 UI；使用 [TotalCross](https://totalcross.com/) 在设备上呈现 Android XML；采用被称为 [KnowCode](https://github.com/TotalCross/KnowCodeXML) 的新 [TotalCross API](https://yourapp.totalcross.com/knowcode-app)；以及使用 [树莓派 4](https://www.raspberrypi.org/) 来执行应用程序。


### 选择 Android Studio


可以使用 TotalCross API 为应用程序构建一个美观的响应式用户体验，但是在 Android Studio 中创建 UI 缩短了制作原型和实际应用程序之间的时间。


有很多工具可以用来为应用程序构建 UI，但是 [Android Studio](https://developer.android.com/studio) 是全世界开发者最常使用的工具。除了它被大量采用以外，这个工具的使用也非常直观，而且它对于创建简单和复杂的应用程序都非常强大。在我看来，唯一的缺点是使用该工具所需的计算机性能，它比其他集成开发环境 （IDE） 如 VSCode 或其开源替代方案 [VSCodium](https://vscodium.com/) 要庞大得多。


通过思考这些问题，我们创建了一个概念验证，使用 Android Studio 绘制 UI，并使用 TotalCross 直接在设备上运行 AndroidXML。


### 构建 UI


对于我们的 PoC，我们想创建一个家用电器应用程序来控制温度和其他东西，并在 Linux ARM 设备上运行。


![Home appliance application to control thermostat](/data/attachment/album/202102/18/123754nxtt51tgtg21jht5.png "Home appliance application to control thermostat")


我们想为树莓派开发我们的应用程序，所以我们使用 Android 的 [ConstraintLayout](https://codelabs.developers.google.com/codelabs/constraint-layout/index.html#0) 来构建 848x480（树莓派的分辨率）的固定屏幕大小的 UI，不过你可以用其他布局构建响应性 UI。


Android XML 为 UI 创建增加了很多灵活性，使得为应用程序构建丰富的用户体验变得容易。在下面的 XML 中，我们使用了两个主要组件：[ImageView](https://developer.android.com/reference/android/widget/ImageView) 和 [TextView](https://developer.android.com/reference/android/widget/TextView)。



```
<ImageView
android:id="@+id/imageView6"
android:layout_width="273dp"
android:layout_height="291dp"
android:background="@drawable/Casa"
tools:layout_editor_absoluteX="109dp"
tools:layout_editor_absoluteY="95dp" />
<TextView
android:id="@+id/insideTempEdit"
android:layout_width="94dp"
android:layout_height="92dp"
android:background="#F5F5F5"
android:text="20"
android:textAlignment="center"
android:gravity="center"
android:textColor="#000000"
android:textSize="67dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="196dp"
tools:layout_editor_absoluteY="246dp" />

```

TextView 元素用于向用户显示一些数据，比如建筑物内的温度。大多数 ImageView 都用作用户与 UI 交互的按钮，但它们也需要实现屏幕上组件提供的事件。


### 用 TotalCross 整合


这个 PoC 中的第二项技术是 TotalCross。我们不想在设备上使用 Android 的任何东西，因为：


1。我们的目标是为 Linux ARM 提供一个出色的 UI。 2。我们希望在设备上实现低占用。 3。我们希望应用程序在低计算能力的低端硬件设备上运行（例如，没有 GPU、 低 RAM 等）。


首先，我们使用 [VSCode 插件](https://medium.com/totalcross-community/totalcross-plugin-for-vscode-4f45da146a0a) 创建了一个空的 TotalCross 项目。接下来，我们保存了 `drawable` 文件夹中的图像副本和 `xml` 文件夹中的 Android XML 文件副本，这两个文件夹都位于 `resources` 文件夹中：


![Home Appliance file structure](/data/attachment/album/202102/18/123754n22li8268d82s882.png "Home Appliance file structure")


为了使用 TotalCross 模拟器运行 XML 文件，我们添加了一个名为 KnowCode 的新 TotalCross API 和一个主窗口来加载 XML。下面的代码使用 API 加载和呈现 XML：



```
public void initUI() {
    XmlScreenAbstractLayout xmlCont = XmlScreenFactory.create("xml / homeApplianceXML.xml");
    swap(xmlCont);
}

```

就这样！只需两个命令，我们就可以使用 TotalCross 运行 Android XML 文件。以下是 XML 如何在 TotalCross 的模拟器上执行：


![TotalCross simulator running temperature application](/data/attachment/album/202102/18/123755zcjpqmjj7v4o7dol.png "TotalCross simulator running temperature application")


完成这个 PoC 还有两件事要做：添加一些事件来提供用户交互，并在树莓派上运行它。


### 添加事件


KnowCode API 提供了一种通过 ID（`getControlByID`） 获取 XML 元素并更改其行为的方法，如添加事件、更改可见性等。


例如，为了使用户能够改变家中或其他建筑物的温度，我们在 UI 底部放置了加号和减号按钮，并在每次单击按钮时都会出现“单击”事件，使温度升高或降低一度：



```
Button plus = (Button) xmlCont.getControlByID("@+id/plus");
Label insideTempLabel = (Label) xmlCont.getControlByID("@+id/insideTempLabel");
plus.addPressListener(new PressListener() {
    @Override
    public void controlPressed(ControlEvent e) {
        try {
            String tempString = insideTempLabel.getText();
            int temp;
            temp = Convert.toInt(tempString);
            insideTempLabel.setText(Convert.toString(++temp));
        } catch (InvalidNumberException e1) {
            e1.printStackTrace();
        }
    }
});

```

### 在树莓派 4 上测试


最后一步！我们在一台设备上运行了应用程序并检查了结果。我们只需要打包应用程序并在目标设备上部署和运行它。[VNC](https://tigervnc.org/) 也可用于检查设备上的应用程序。


整个应用程序，包括资源（图像等）、Android XML、TotalCross 和 Knowcode API，在 Linux ARM 上大约是 8MB。


下面是应用程序的演示：


![Application demo](/data/attachment/album/202102/18/123755iasg8auh22sk2d11.gif "Application demo")


在本例中，该应用程序仅为 Linux ARM 打包，但同一应用程序可以作为 Linux 桌面应用程序运行，在Android 设备 、Windows、windows CE 甚至 iOS 上运行。


所有示例源代码和项目都可以在 [HomeApplianceXML GitHub](https://github.com/TotalCross/HomeApplianceXML) 存储库中找到。


### 现有工具的新玩法


为嵌入式应用程序创建 GUI 并不需要像现在这样困难。这种概念证明为如何轻松地完成这项任务提供了新的视角，不仅适用于嵌入式系统，而且适用于所有主要的操作系统，所有这些系统都使用相同的代码库。


我们的目标不是为设计人员或开发人员创建一个新的工具来构建 UI 应用程序；我们的目标是为使用现有的最佳工具提供新的玩法。


你对这种新的应用程序开发方式有何看法？在下面的评论中分享你的想法。




---


via: <https://opensource.com/article/20/5/linux-arm-ui>


作者：[Bruno Muniz](https://opensource.com/users/brunoamuniz) 选题：[lujun9972](https://github.com/lujun9972) 译者：[Chao-zhi](https://github.com/Chao-zhi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Creating a great user experience (UX) for your applications is a tough job, especially if you are developing embedded applications. Today, there are two types of graphical user interface (GUI) tools generally available for developing embedded software: either they involve complex technologies, or they are extremely expensive.

However, we have created a proof of concept (PoC) for a new way to use existing, well-established tools to build user interfaces (UIs) for applications that run on desktop, mobile, embedded devices, and low-power Linux ARM devices. Our method uses Android Studio to draw the UI; [TotalCross](https://totalcross.com/) to render the Android XML on the device; a new [TotalCross API](https://yourapp.totalcross.com/knowcode-app) called [KnowCode](https://github.com/TotalCross/KnowCodeXML); and a [Raspberry Pi 4](https://www.raspberrypi.org/) to execute the application.

## Choosing Android Studio

It's possible to build a responsive and beautiful UX for an application using the TotalCross API, but creating the UI in Android Studio shortens the time between prototyping and the real application.

There are a lot of tools available to build UIs for applications, but [Android Studio](https://developer.android.com/studio) is the one developers worldwide use most often. In addition to its massive adoption, this tool is also super-intuitive to use, and it's really powerful for creating both simple and complex applications. The only drawback, in my opinion, is the computing power required to use the tool, which is way heavier than other integrated development environments (IDEs) like VSCode or its open source alternative, [VSCodium](https://vscodium.com/).

By thinking through these issues, we created a proof of concept using Android Studio to draw the UI and TotalCross to run the Android XML directly on the device.

## Building the UI

For our PoC, we wanted to create a home-appliance application to control temperature and other things and that would run on a Linux ARM device.

![Home appliance application to control thermostat Home appliance application to control thermostat](https://opensource.com/sites/default/files/uploads/homeapplianceapp.png)

(Bruno Muniz, CC BY-SA 4.0)

We wanted to develop our application for a Raspberry Pi, so we used Android's [ConstraintLayout](https://codelabs.developers.google.com/codelabs/constraint-layout/index.html#0) to build a fixed-screen-size UI of 848x480 (the Raspberry Pi's resolution), but you can build responsive UIs with other layouts.

Android XML adds a lot of flexibility for UI creation, making it easy to build rich user experiences for applications. In the XML below, we used two main components: [ImageView](https://developer.android.com/reference/android/widget/ImageView) and [TextView](https://developer.android.com/reference/android/widget/TextView).

```
<ImageView
android:id="@+id/imageView6"
android:layout_width="273dp"
android:layout_height="291dp"
android:background="@drawable/Casa"
tools:layout_editor_absoluteX="109dp"
tools:layout_editor_absoluteY="95dp" />
<TextView
android:id="@+id/insideTempEdit"
android:layout_width="94dp"
android:layout_height="92dp"
android:background="#F5F5F5"
android:text="20"
android:textAlignment="center"
android:gravity="center"
android:textColor="#000000"
android:textSize="67dp"
android:textStyle="bold"
tools:layout_editor_absoluteX="196dp"
tools:layout_editor_absoluteY="246dp" />
```


The TextView elements are used to show some data to the user, like the temperature inside a building. Most ImageViews are used as buttons for user interaction with the UI, but they're also needed to implement the Events provided by the components on the screen.

## Integrating with TotalCross

The second technology in this PoC is TotalCross. We don't want to use anything from Android on the device because:

- Our goal is to provide a great UI for Linux ARM.
- We want to achieve a low footprint on the device.
- We want the application to run on low-end hardware devices with low computing power (e.g., no GPU, low RAM, etc.).

To begin, we created an empty TotalCross project using our [VSCode plugin](https://medium.com/totalcross-community/totalcross-plugin-for-vscode-4f45da146a0a). Next, we saved a copy of the images inside the **drawable** folder and a copy of the Android XML file inside the **XML** folder—both are located inside the **Resources** folder:

![Home Appliance file structure Home Appliance file structure](https://opensource.com/sites/default/files/uploads/homeappliancexml.png)

(Bruno Muniz, CC BY-SA 4.0)

To run the XML file using the TotalCross Simulator, we added a new TotalCross API called KnowCode and a MainWindow to load the XML. The code below uses the API to load and render the XML:

```
public void initUI() {
XmlScreenAbstractLayout xmlCont = XmlScreenFactory.create(“xml / homeApplianceXML.xml”);
swap(xmlCont);
}
```


That's it! With only two commands, we can run an Android XML file using TotalCross. Here is how the XML performs on TotalCross' simulator:

![TotalCross simulator running temperature application TotalCross simulator running temperature application](https://opensource.com/sites/default/files/uploads/totalcross-simulator_0.png)

(Bruno Muniz, CC BY-SA 4.0)

There are two things remaining to finish this PoC: adding some events to provide user interaction and running it on a Raspberry Pi.

## Adding events

The KnowCode API provides a way to get an XML element by its ID (getControlByID) and change its behavior to do things like adding events, changing visibility, and more.

For example, to enable users to change the temperature in their home or other building, we put plus and minus buttons on the bottom of the UI and a "click" event that increases or decreases the temperature one degree every time the buttons are clicked:

```
Button plus = (Button) xmlCont.getControlByID("@+id/plus");
Label insideTempLabel = (Label) xmlCont.getControlByID("@+id/insideTempLabel");
plus.addPressListener(new PressListener() {
@Override
public void controlPressed(ControlEvent e) {
try {
String tempString = insideTempLabel.getText();
int temp;
temp = Convert.toInt(tempString);
insideTempLabel.setText(Convert.toString(++temp));
} catch (InvalidNumberException e1) {
e1.printStackTrace();
}
}
});
```


## Testing on a Raspberry Pi 4

Finally, the last step! We ran the application on a device and checked the results. We just needed to package the application and deploy and run it on the target device. A [VNC](https://tigervnc.org/) can also be used to check the application on the device.

The entire application, including assets (images, etc.), Android XML, TotalCross, and the KnowCode API, is about 8MB on Linux ARM.

Here's a demo of the application:

![Application demo Application demo](https://opensource.com/sites/default/files/uploads/application.gif)

(Bruno Muniz, CC BY-SA 4.0)


In this example, the application was packaged only for Linux ARM, but the same app will run as a Linux desktop app, Android devices, Windows, Windows CE, and even iOS.

All of the sample source code and the project are available in the [HomeApplianceXML GitHub](https://github.com/TotalCross/HomeApplianceXML) repository.

## New possibilities with existing tools

Creating GUIs for embedded applications doesn't need to be as hard as it is today. This proof of concept brings a new perspective on how to do this task easily—not only for embedded systems but for all major operating systems, all using the same code base.

We are not aiming to create a new tool for designers or developers to build UI applications; our goal is to provide new possibilities for using the best tools that are already available.

What's your opinion of this new way to build apps? Share your thoughts in the comments below.

## 2 Comments