1Personalizar el diseño del cuadro de diálogo
1.1 Descripción del problema
¿Cómo implementar un diálogo personalizado?
1.2 Método de implementación
Agregar código de diálogo personalizado
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();
Personalizar el archivo de diseño de 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标题"
ohos:text_color="$color:Black"
ohos:text_style="bold"
ohos:text_size="40fp"/>
<Text
ohos:width="match_parent"
ohos:height="match_parent"
ohos:text="自定义Dialog内容"
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="取消"
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="确定"
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 Efecto real
2 Establezca el color de fondo del control
2.1 Descripción del problema
La configuración del control ohos: background_element = "$ color: yellow" en el diseño xml no es válida. Actualmente, el color de fondo no admite la configuración de $ color, pero solo admite la configuración de $ graphic.
2.2 Método de implementación
Método 1: use $ graphic para establecer el color de fondo del control en xml
<Button
ohos:width="match_parent"
ohos:text="控件按钮"
ohos:text_size="30fp"
ohos:padding="10vp"
ohos:text_color="$color:White"
ohos:background_element="$graphic:yellow"
ohos:height="match_content"/>
El código yellow.xml en el gráfico del archivo de recursos es el siguiente:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid
ohos:color="#fff9a825"/>
</shape>
Método 2: establecer el color del control en código puro
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添加背景");
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 Efecto real
3 ScrollView anidado DirectionalLayout para desplazarse
3.1 Descripción del problema
¿Cómo se desplaza ScrollView anidado DirectionalLayout?
3.2 Método de implementación
- Para usar el diseño xml, debe establecer la altura de ScrollView en "match_parent" y la altura del sub-diseño de ScrollView en "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>
- Use el código para agregar, debe configurar LayoutConfig para ScrollView y el sub-diseño
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 Efecto real
4 Cargue y muestre imágenes de red
4.1 Descripción del problema
¿Cómo cargar y mostrar imágenes de red?
4.2 Método de implementación
- Agregar permisos de red en config.json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
- Obtener y configurar imágenes de red
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();
// 之后可进行url的其他操作
// 得到服务器返回过来的流对象
InputStream inputStream = urlConnection.getInputStream();
ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
// 普通解码叠加旋转、缩放、裁剪
PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
// 普通解码
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 Efecto real
5 Uso del componente de lista ListContainer
5.1 Descripción del problema
¿Cómo utilizar el componente de lista ListContainer?
5.2 Método de implementación
Declare el componente en el archivo xml
<?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>
Obtenga el componente ListContainer y configure el itemProvider
private void initView() {
mListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
ListItemProvider listItemProvider = new ListItemProvider();
mListContainer.setItemProvider(listItemProvider);
}
Custom ListItemProvider hereda 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 Efecto real
6 Lea el archivo de recursos
6.1 Descripción del problema
¿Cómo leer los archivos de recursos de la aplicación?
6.2 Método de implementación
- Para los archivos de imagen, se recomienda colocarlos en el directorio base / media. El componente Imagen se puede configurar directamente de la siguiente manera.
Image image = (Image) findComponentById(ResourceTable.Id_component_image);
image.setPixelMap(ResourceTable.Media_huawei);
- Para leer y escribir archivos sin formato, consulte el siguiente método:
ohos.global.resource.ResourceManager resourceManager = getApplicationContext().getResourceManager();
ohos.global.resource.RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/rawfile/test.png");
RawFileDescriptor rawFileDescriptor = rawFileEntry.openRawFileDescriptor();
// 或者
Resource resource = rawFileEntry.openRawFile();
6.3 Efecto real
7 método JS para obtener información de ubicación
7.1 Descripción del problema
¿Cómo obtener información de ubicación al usar el desarrollo JS?
7.2 Método de implementación
- Importe el módulo get location y llame al método getLocation para obtener información de ubicación
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");
}
});
}
}
- Aumente el permiso para obtener información de ubicación en config.json
"reqPermissions": [
{
"name": "ohos.permission.LOCATION"
}
],
7.3 Efecto real
8 Desactive el deslizamiento izquierdo y derecho del sistema en el reloj.
8.1 Descripción del problema
Desarrolle una aplicación que admita operaciones de deslizamiento hacia la izquierda y hacia la derecha, pero cuando deslice hacia la derecha en el emulador, irá por defecto a la página del sistema y saldrá de la aplicación ¿Cómo deshabilitar el deslizamiento hacia la derecha del sistema?
8.2 Método de implementación
Anule el método onTouchEvent en MainAbility, la implementación es la siguiente
@Override
protected boolean onTouchEvent(TouchEvent event) {
super.onTouchEvent(event);
return true;
}
8.3 Efecto real
9 Ajustar texto en el control de texto
9.1 Descripción del problema
El texto en el control de texto no admite actualmente el ajuste de \ nlínea, ¿cómo se ajusta?
9.2 Método de implementación
Puede utilizar el sistema para ajustar automáticamente para mantener las dos líneas de texto con la misma longitud. La realización es la siguiente
<?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="目前车辆尊享服务已过期, 车主续费后才可继续使用"/>
</DirectionalLayout>
9.3 Efecto real
10 Introduzca otros archivos de diseño xml en un diseño xml
10.1 Descripción del problema
Se define un archivo de diseño XML público ¿Cómo hacer referencia a este archivo de diseño XML público en otros archivos de diseño XML?
10.2 Método de implementación
Puede hacer referencia a otros archivos de diseño XML a través de la etiqueta de inclusión, un ejemplo es el siguiente:
<?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 Resultados reales
N / A
11 Personaliza el color del control Swtich
11.1 Descripción del problema
¿Cómo personalizar el color de los botones en el interruptor de dos estados del control Swtich?
11.2 Método de implementación
Cree bg_element.xml y fg_element.xml en el archivo gráfico del archivo de recursos. El contenido del archivo bg_element.xml es el siguiente
<?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>
El contenido del archivo fg_element.xml es el siguiente
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="oval">
<solid
ohos:color="#D81B60"/>
</shape>
Código para implementar colores personalizados:
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 Resultados reales
12 Reproducción de video
12.1 Descripción del problema
¿Cómo reproducir archivos de video locales y videos en red?
12.2 Método de implementación
Cree un archivo de diseño video_player_layout.xml con el siguiente contenido
<?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>
Defina las siguientes variables, los contenidos son los siguientes:
private static Player mPlayer;
private SurfaceProvider mSurfaceProvider;
private DependentLayout mLayout;
Para implementar la interfaz SurfaceOps.Callback, el código es el siguiente:
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.");
}
}
Para implementar la interfaz Player.IplayerCallback, el código es el siguiente:
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");
}
}
Descubra el método de reproducción de archivos locales, donde el archivo test.mp4 se coloca en el directorio de archivos de recursos, y el contenido es el siguiente:
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());
}
}
Un método para reproducir una URL de red, donde la URL de video es una URL de recurso de video y el contenido es el siguiente:
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());
}
}
Para reproducir videos en línea, debe solicitar permisos de uso de la red. Agregue el siguiente contenido a config.json:
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
},
]
12.3 Efecto real
Enlace original:https://developer.huawei.com/consumer/cn/forum/topic/0204410755673870341?fid=0101303901040230869
Autor: eva3w