Official summary of common problems and typical cases of implementation methods of Hongmeng application development

1. Customize the layout of Dialog

1.1 problem description

How to implement a custom Dialog?

1.2 implementation method

Add custom Dialog code

CommonDialog commonDialog = new   CommonDialog(this);
 
Component component =   LayoutScatter.getInstance(getContext())
 
                   .parse(ResourceTable.Layout_dialog_custom_layout,   null, true);
 
commonDialog.setSize(800, 500);
 
commonDialog.setContentCustomComponent(component);

commonDialog.show();

Customize the layout file of Dialog

<?xml version="1.0"   encoding="utf-8"?>

<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos" 
                     ohos:width="match_parent"
                     ohos:height="match_content"
                     ohos:padding="10vp"
                     ohos:background_element="@graphic:grey"
                   ohos:orientation="vertical">
                   
      <Text
              ohos:width="match_parent"
              ohos:height="match_content"
              ohos:text="Dialog title"
              ohos:text_color="$color:Black"
              ohos:text_style="bold"
              ohos:text_size="40fp"/>

      <Text 
              ohos:width="match_parent"
              ohos:height="match_parent"
              ohos:text="custom Dialog content"
              ohos:text_color="$color:Black" 
              ohos:text_style="bold"
              ohos:weight="1"
              ohos:text_alignment="vertical_center"
              ohos:top_margin="30vp"
              ohos:bottom_margin="30vp"
              ohos:left_margin="10vp"
              ohos:right_margin="10vp"
              ohos:text_size="30fp"/>

      <DirectionalLayout 
              ohos:height="match_content"
              ohos:width="match_parent"
              ohos:orientation="horizontal">

       <Button
              ohos:width="match_parent"
              ohos:text="cancel"
              ohos:text_size="30fp"
              ohos:padding="10vp"
              ohos:text_color="$color:White"
              ohos:weight="1"
              ohos:margin="10vp"
              ohos:background_element="$graphic:yellow"
              ohos:height="match_content"/>

        <Button
              ohos:width="match_parent"
              ohos:text="determine"
              ohos:text_size="30fp"
              ohos:weight="1"
              ohos:padding="10vp"
              ohos:text_color="$color:White"
              ohos:margin="10vp"
              ohos:background_element="$graphic:green"
              ohos:height="match_content"/>
      </DirectionalLayout>
</DirectionalLayout>

1.3 actual effect

2 set the background color of the control

2.1 problem description

Setting control ohos: background in xml layout_ Element = "$color: yellow" is invalid. At present, the background color does not support setting in the way of $color, but only in the way of $graphic.

2.2 implementation method

Method 1: set the control background color in xml and use $graphic

<Button
      ohos:width="match_parent"
      ohos:text="Control button"
      ohos:text_size="30fp"
      ohos:padding="10vp"
      ohos:text_color="$color:White"
      ohos:background_element="$graphic:yellow"
      ohos:height="match_content"/>

Yellow. In the resource file graphic The XML code is as follows:

<?xml version="1.0"   encoding="utf-8"?>
<shape   xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">  
    <solid
        ohos:color="#fff9a825"/>
</shape>

Method 2: set the control color in pure code

DirectionalLayout.LayoutConfig   config = new   DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT,   DirectionalLayout.LayoutConfig.MATCH_CONTENT);

config.setMargins(30, 10, 10, 10); 
ShapeElement element = new   ShapeElement();
element.setRgbColor(new RgbColor(255,   111, 0));
Text text = new Text(this);
text.setText("xml Add background");
text.setTextColor(new Color(0xFFFFFFFF));
text.setTextSize(40);
text.setPadding(30, 20, 30, 20);
text.setTextAlignment(TextAlignment.CENTER);
text.setBackground(element);
text.setLayoutConfig(config);

2.3 actual effect

3 Scrollview nested DirectionalLayout to scroll

3.1 problem description

How does ScrollView nested DirectionalLayout scroll?

3.2 implementation method

  1. To use xml layout, you need to set the height of ScrollView to "match_parent", and the height of ScrollView sub layout to "match_content"
<?xml version="1.0" encoding="utf-8"?>

<ScrollView 
          xmlns:ohos="http://schemas.huawei.com/res/ohos"
          ohos:width="match_parent"
          ohos:height="match_parent"
          ohos:orientation="vertical">
          
      <DirectionalLayout   xmlns:ohos="http://schemas.huawei.com/res/ohos"
                         ohos:width="match_parent"
                         ohos:height="match_content"
                         ohos:orientation="vertical">
         ...
      </DirectionalLayout>
</ScrollView>
  1. Using code addition, you need to set LayoutConfig for ScrollView and sub layout
ComponentContainer.LayoutConfig   scrollConfig = new   ComponentContainer.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT,   DirectionalLayout.LayoutConfig.MATCH_PARENT);

scrollView.setLayoutConfig(scrollConfig);
 
DirectionalLayout.LayoutConfig config =   new   DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_PARENT,   DirectionalLayout.LayoutConfig.MATCH_CONTENT);
 
myLayout.setLayoutConfig(config);
 
...
 
scrollView.addComponent(myLayout);
 
super.setUIContent(scrollView); 

3.3 actual effect

4 load and display network pictures

4.1 problem description

How to load and display network pictures?

4.2 implementation method

  1. In config Add network permissions to JSON
{
    "module": {
      "reqPermissions": [
        {
          "name": "ohos.permission.INTERNET"
        }
      ]
  }
}
  1. Get and set network pictures
String   urlImage = "https://www.harmonyos.com/resource/image/community/20201009-164134eSpace.jpg";

HttpURLConnection   connection = null;
 
try {
         URL url = new URL(urlImage);
         URLConnection urlConnection =   url.openConnection();
         if (urlConnection instanceof   HttpURLConnection) {
                   connection =   (HttpURLConnection) urlConnection;
         }
         if (connection != null) {
                   connection.connect();
                   // After that, you can perform other operations on the url
                   // Get the stream object returned by the server
                   InputStream inputStream =   urlConnection.getInputStream();
                   ImageSource imageSource = ImageSource.create(inputStream,   new ImageSource.SourceOptions());
                   ImageSource.DecodingOptions   decodingOptions = new ImageSource.DecodingOptions();
                   decodingOptions.desiredPixelFormat   = PixelFormat.ARGB_8888;
                   // General decoding overlay rotation, scaling and clipping
                   PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
                   // General decoding
                   getUITaskDispatcher().syncDispatch(()   -> {
                            Image image = new   Image(HttpImageSlice.this);
                            DirectionalLayout.LayoutConfig   config = new DirectionalLayout.LayoutConfig(DirectionalLayout.LayoutConfig.MATCH_CONTENT,   DirectionalLayout.LayoutConfig.MATCH_CONTENT);
                       config.setMargins(10, 10,   10, 10);
                            image.setLayoutConfig(config);
                            image.setPixelMap(pixelMap);
                            myLayout.addComponent(image);
                            pixelMap.release();
                   });
         }

}   catch (Exception e) { 
         e.printStackTrace();
}

4.3 actual effect

5 use of listcontainer list component

5.1 problem description

How is the ListContainer list component used?

5.2 implementation method

Declare components in an xml file

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:width="match_parent"
        ohos:height="match_parent"
        ohos:orientation="vertical">

    <ListContainer
            ohos:id="$+id:list_container"
            ohos:orientation="vertical"
            ohos:width="match_parent"
            ohos:height="match_parent"/>
</DirectionalLayout>

Get ListContainer component and set itemProvider

private void initView() {
mListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
ListItemProvider listItemProvider = new ListItemProvider();
mListContainer.setItemProvider(listItemProvider);
}

Custom ListItemProvider inherits RecycleItemProvider

class ListItemProvider extends RecycleItemProvider {
    @Override
    public int getCount() {
        return data.size();
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }
    @Override
    public Component getComponent(int position, Component convertView, ComponentContainer componentContainer) {
        Component component = LayoutScatter.getInstance(getContext())
                .parse(ResourceTable.Layout_layout_container_item, null, false);
        if (!(component instanceof ComponentContainer)) {
            return null;
        }
        ComponentContainer rootLayout = (ComponentContainer) component;
        Text rightText = (Text) rootLayout.findComponentById(ResourceTable.Id_content);
        rightText.setText(data.get(position));
        return component;
    }
}

5.3 actual effect

6 read resource file

6.1 problem description

How to read the application resource file?

6.2 implementation method

  1. For Image files, it is recommended to put them in the base/media directory. The Image component can be set directly. The method is as follows.
Image image = (Image) findComponentById(ResourceTable.Id_component_image);
image.setPixelMap(ResourceTable.Media_huawei);
  1. For the reading and writing of rawfile files, please refer to the following methods:
ohos.global.resource.ResourceManager resourceManager = getApplicationContext().getResourceManager();
ohos.global.resource.RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/rawfile/test.png");
RawFileDescriptor rawFileDescriptor = rawFileEntry.openRawFileDescriptor();
// perhaps
Resource resource = rawFileEntry.openRawFile();

6.3 actual effect

7 JS method to obtain location information

7.1 problem description

How to obtain location information when developing with JS?

7.2 implementation method

  1. Import the location module and call the getLocation method to obtain the location information
import geolocation from '@system.geolocation';
export default {
    data: {
        longitude: 0.0,
        latitude: 0.0
    },
    onInit() {
        this.getLocation();
    },
    getLocation() {
        var temp = this;
        geolocation.getLocation({
            success: function(data) {
                console.info("get location success, longitude: " + data.longitude +", latitude: " + data.latitude);
                temp.longitude = data.longitude
                temp.latitude = data.latitude;
            },
            fail: function(data, code) {
                console.error("get location failed, code: " + code + ",  data: " + data);
            },
            complete: function() {
                console.info("get location complete");
            }
        });
    }
}
  1. In config Add permission to get location information in JSON
"reqPermissions": [
  {
    "name": "ohos.permission.LOCATION"
  }
],

7.3 actual effect

8 disable the left and right sliding of the system in the watch

8.1 problem description

Developing an application supports the operation of sliding left and right, but when sliding right in the simulator, it will jump to the system page by default and exit the application. How to disable the system sliding right?

8.2 implementation method

Override the onTouchEvent method in MainAbility, and the implementation is as follows

@Override
protected boolean onTouchEvent(TouchEvent event) {
    super.onTouchEvent(event);
    return true;
}

8.3 actual effect

9 text wrapping in text control

9.1 problem description

The Text in the Text control does not support line wrapping at present. How to wrap?

9.2 implementation method

You can use the system to automatically wrap lines and keep the length of two lines of text consistent. The implementation is as follows:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
                   ohos:width="match_parent"
                   ohos:height="match_parent"
                   ohos:orientation="vertical">
    <Text
            ohos:id="$+id:text"
            ohos:width="150vp"
            ohos:height="match_content"
            ohos:multiple_lines="true"
            ohos:max_text_lines="2"
            ohos:auto_font_size="true"
            ohos:text="At present, the vehicle exclusive service has expired, The owner can only continue to use it after renewing the fee"/>
</DirectionalLayout>

9.3 actual effect

10 introducing other xml layout files into one layout xml

10.1 problem description

A public XML layout file is defined. How can this public XML layout file be referenced in other XML layout files?

10.2 implementation method

Other XML layout files can be referenced through the include tag, for example:

<?xml version="1.0" encoding="utf-8"?>
<include ohos:id="$+id:include_layout"
             ohos:layout="$layout:include_layout"
             ohos:width="match_parent"
             ohos:height="match_content"/>
</DirectionalLayout>

10.3 actual effect

NA

11 customize the color of Swtich control

11.1 problem description

How to customize the button color in two states of the switch of Swtich control?

11.2 implementation method

Create BG under resource file graphic file_ element. XML and fg_element.xml,bg_ element. The contents of the XML file are as follows

<?xml version="1.0" encoding="utf-8"?>

<shape
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:shape="rectangle">

    <corners
            ohos:radius="30"/>
    <solid
            ohos:color="#424242"/>
</shape>

fg_ element. The contents of the XML file are as follows

<?xml version="1.0" encoding="utf-8"?>

<shape
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:shape="oval">
    <solid
            ohos:color="#D81B60"/>
</shape>

Code implementation custom color:

private void setupSwitch() {

    mSwitch = (Switch) findComponentById(ResourceTable.Id_switch_custom);

    Element elementBackground = ElementScatter.getInstance(this).parse(ResourceTable.Graphic_bg_element);

    mSwitch.setTrackElement(elementBackground);

    Element elementThumb = ElementScatter.getInstance(this).parse(ResourceTable.Graphic_fg_element);

    mSwitch.setThumbElement(elementThumb);

    mSwitch.setClickedListener(new Component.ClickedListener() {

        @Override

        public void onClick(Component component) {

            Log.i("switch: " + mSwitch.isChecked());

        }

    });

}

11.3 actual effect

12 video playback

12.1 problem description

How to play local video files and network videos?

12.2 implementation method

Create layout file video_player_layout.xml, as follows

<?xml version="1.0" encoding="utf-8"?>

<DependentLayout xmlns:ohos="http://schemas.huawei.com/res/ohos"
                   ohos:id="$+id:video_player_dl"
                   ohos:width="match_parent"
                   ohos:height="match_parent"
                   ohos:orientation="vertical">
</DependentLayout>

Define the following variables as follows:

private static Player mPlayer;
private SurfaceProvider mSurfaceProvider;
private DependentLayout mLayout;

Implement surfaceops Callback interface, code as follows:

class VideoSurfaceCallback implements SurfaceOps.Callback {
    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {
        Log.i("surfaceCreated() called.");
        if (mSurfaceProvider.getSurfaceOps().isPresent()) {
            Surface surface = mSurfaceProvider.getSurfaceOps().get().getSurface();
            playUrl(surface);
        }
    }
    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {
        Log.i("surfaceChanged() called.");
    }
    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {
        Log.i("surfaceDestroyed() called.");
    }
}

Implement player Iplayercallback interface, the code is as follows:

private class VideoPlayerCallback implements Player.IPlayerCallback {
    @Override
    public void onPrepared() {
        Log.i("onPrepared");
    }
    @Override
    public void onMessage(int i, int i1) {
        Log.i("onMessage");
    }
    @Override
    public void onError(int i, int i1) {
        Log.i("onError: i=" + i + ", i1=" + i1);
    }
    @Override
    public void onResolutionChanged(int i, int i1) {
        Log.i("onResolutionChanged");
    }
    @Override
    public void onPlayBackComplete() {
        Log.i("onPlayBackComplete");
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer = null;
        }
    }
    @Override
    public void onRewindToComplete() {
        Log.i("onRewindToComplete");
    }
    @Override
    public void onBufferingChange(int i) {
        Log.i("onBufferingChange");
    }
    @Override
    public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
        Log.i("onNewTimedMetaData");
    }
    @Override
    public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
        Log.i("onMediaTimeIncontinuity");
    }
}

Implement the method of playing local files, where test The MP4 file is placed in the resource file directory. The contents are as follows:

private void playLocalFile(Surface surface) {
    try {
        RawFileDescriptor filDescriptor = getResourceManager().getRawFileEntry("resources/rawfile/test.mp4").openRawFileDescriptor();
        Source source = new Source(filDescriptor.getFileDescriptor(),filDescriptor.getStartPosition(),filDescriptor.getFileSize());
        mPlayer.setSource(source);
        mPlayer.setVideoSurface(surface);
        mPlayer.setPlayerCallback(new VideoPlayerCallback());
        mPlayer.prepare();
        mSurfaceProvider.setTop(0);
        mPlayer.play();
    } catch (Exception e) {
        Log.e("playUrl Exception:" + e.getMessage());
    }
}

Realize the method of playing network URL, where video url is the URL of video resource, and the content is as follows:

private void playUrl(Surface surface) {

    try {
        Source source = new Source("video url");
        mPlayer.setSource(source);
        mPlayer.setVideoSurface(surface);
        mPlayer.setPlayerCallback(new VideoPlayerCallback());
        mPlayer.prepare();
        mSurfaceProvider.setTop(0);
        mPlayer.play();
    } catch (Exception e) {
        Log.e("playUrl Exception:" + e.getMessage());
    }
}

To play network video, you need to apply for network permission in config Add the following content to JSON:

"reqPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
]

12.3 actual effect

Original link: https://developer.huawei.com/consumer/cn/forum/topic/0204410755673870341?fid=0101303901040230869

Original author: eva3w

Tags: Java watermark shadow element surface

Posted by pouncer on Sat, 07 May 2022 02:12:07 +0300