【JAVA UI】HarmonyOS如何集成picasso加载网络图片

 参考资料

picasso

 

代码实现

1、准备工作

在项目级的bulid.gradle文件添加如下代码

allprojects{
        repositories{
            mavenCentral()
        }
    }

在entry的bulid.gradle文件添加如下代码

 implementation 'io.openharmony.tpc.thirdlib:picasso:1.0.4'

2、设置权限

在confing.json添加权限,代码如下

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

在config.json修改deviceConfig的代码,代码如下

 "deviceConfig": {
    "default": {
      "network": {
        "cleartextTraffic": true
      }
    }
  },

3、xml布局

在xml添加一个Image组件代码如下

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

    <Image
        ohos:height="200vp"
        ohos:width="match_parent"
        ohos:image_src="#ed6262"
        ohos:id="$+id:myImage"/>

</DirectionalLayout>

4、java代码实现

在java 代码中查这个组件然后调用项目api去加载网络图片,代码如下

package com.newdemo.myapplication.slice;

import com.newdemo.myapplication.ResourceTable;
import com.squareup.picasso.Picasso;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //todo 查找Image组件
        Image myimage=findComponentById(ResourceTable.Id_myImage);
        Picasso.get()
                //todo 加载网络图片
                .load("https://www.baidu.com/img/flexible/logo/pc/result.png")
             //todo 空的占位图
                .placeholder(ResourceTable.Media_icon)
                //todo 加载错误的图片
                .error(ResourceTable.Media_icon)
                //todo 加载组件上
                .into(myimage);
    }

}

 

运行效果

cke_20326.png

欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章