1自定義Dialog的布局
1.1 問題描述
如何實現自定義的Dialog?
1.2 實現方法
添加自定義Dialog代碼
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();
自定義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 實際效果
2 設置控件背景顏色
2.1 問題描述
在xml布局中設置控件ohos:background_element="$color:yellow"無效,目前背景顏色不支持以$color方式設置,只支持$graphic方式設置。
2.2 實現方法
方式1:xml中設置控件背景顏色使用$graphic
<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"/>
資源文件graphic中yellow.xml代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid
ohos:color="#fff9a825"/>
</shape>
方式2:純代碼設置控件顏色
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 實際效果
3 ScrollView嵌套DirectionalLayout進行滾動
3.1 問題描述
ScrollView嵌套DirectionalLayout如何進行滾動?
3.2 實現方法
- 使用xml布局,需要將ScrollView的高度設置成“match_parent”,ScrollView子布局的高度設置成“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>
- 使用代碼添加,則需要給ScrollView和子布局設置LayoutConfig
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 實際效果
4 加載和顯示網絡圖片
4.1 問題描述
如何實現加載和顯示網絡圖片?
4.2 實現方法
- 在config.json中添加網絡權限
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
- 獲取並設置網絡圖片
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 實際效果
5 ListContainer列表組件的使用
5.1 問題描述
ListContainer列表組件如何使用?
5.2 實現方法
在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>
獲取 ListContainer 組件,並設置itemProvider
private void initView() {
mListContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
ListItemProvider listItemProvider = new ListItemProvider();
mListContainer.setItemProvider(listItemProvider);
}
自定義 ListItemProvider 繼承 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 實際效果
6 讀取資源文件
6.1 問題描述
如何讀取應用的資源文件?
6.2 實現方法
- 對於圖片文件,建議放到base/media目錄下,Image組件可以直接設置,方法如下。
Image image = (Image) findComponentById(ResourceTable.Id_component_image);
image.setPixelMap(ResourceTable.Media_huawei);
- 對於rawfile文件的讀寫,請參考下面的方法:
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 實際效果
7 JS方法獲取位置信息
7.1 問題描述
使用JS開發時,如何獲取位置信息?
7.2 實現方法
- 導入獲取位置模塊,並調用getLocation方法獲取位置信息
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");
}
});
}
}
- 在config.json中增加獲取位置信息的權限
"reqPermissions": [
{
"name": "ohos.permission.LOCATION"
}
],
7.3 實際效果
8 禁用手表中系統的左右滑動
8.1 問題描述
開發一個應用支持左右滑動的操作,但是在模擬器中右滑時,默認跳轉到系統頁面,並退出應用,如何禁用系統右滑?
8.2 實現方法
覆蓋MainAbility中的onTouchEvent方法,實現如下
@Override
protected boolean onTouchEvent(TouchEvent event) {
super.onTouchEvent(event);
return true;
}
8.3 實際效果
9 Text控件中文字換行
9.1 問題描述
Text控件中文字目前不支持\n換行,如何進行換行?
9.2 實現方法
可以使用系統自動換行,保持兩行文字長度一致,實現如下
<?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 實際效果
10 在一個布局xml中引入其他xml布局文件
10.1 問題描述
定義了一個公共的XML布局文件,如何在其他XML布局文件中引用這個公共的XML布局文件?
10.2 實現方法
可以通過include標簽引用其他的XML布局文件,示例如下:
<?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 實際效果
NA
11 自定義Swtich控件的顏色
11.1 問題描述
如何自定義Swtich控件的開關兩個狀態下的按鈕顏色?
11.2 實現方法
在資源文件graphic文件下創建bg_element.xml和fg_element.xml,bg_element.xml文件內容如下
<?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.xml文件內容如下
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="oval">
<solid
ohos:color="#D81B60"/>
</shape>
代碼實現自定義顏色:
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 實際效果
12 視頻播放
12.1 問題描述
如何播放本地視頻文件和網絡視頻?
12.2 實現方法
創建布局文件video_player_layout.xml,內容如下
<?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>
定義下面的變量,內容如下:
private static Player mPlayer;
private SurfaceProvider mSurfaceProvider;
private DependentLayout mLayout;
實現SurfaceOps.Callback接口,代碼如下:
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.");
}
}
實現Player.IplayerCallback接口,代碼如下:
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");
}
}
實現播放本地文件的方法,其中test.mp4文件放到資源文件目錄下,內容如下:
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());
}
}
實現播放網絡URL的方法,其中video url為視頻資源URL,內容如下:
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());
}
}
播放網絡視頻,需要申請網絡使用權限,在config.json中增加如下內容:
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
},
]
12.3 實際效果
原文鏈接:https://developer.huawei.com/consumer/cn/forum/topic/0204410755673870341?fid=0101303901040230869
原作者:eva3w