You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发中如何将图片加载对应的URL字符串设置到TextView

问题原因

你自定义的ImageLoadTask类中url属性使用了private私有访问修饰符,类的外部无法直接访问该属性,因此直接读取uu.url会编译报错无法运行。同时你提供的代码中没有调用异步任务的execute()方法,图片加载逻辑也不会执行。

解决方法

你可以选择以下任意一种方案实现需求:

方案1:直接复用已有的URL变量

你构造ImageLoadTask时已经持有了URL字符串,直接使用该字符串给TextView赋值即可,无需从异步任务实例中读取,这是最简单的实现方式:

ImageView fff1 = (ImageView) findViewById(R.id.iop1);
TextView hol = (TextView) findViewById(R.id.mytext);
// 提前定义URL变量,多处复用
String imgUrl = "https://maheshwaghela.com/VIPINIH/img/Mahesh/western/mimg10.jpg";
ImageLoadTask uu = new ImageLoadTask(imgUrl, fff1);
// 直接给TextView赋值
hol.setText(imgUrl);
// 启动异步任务加载图片
uu.execute();

方案2:给ImageLoadTask添加公共getter方法

如果后续确实需要从异步任务实例中获取URL属性,可以给ImageLoadTask类添加一个公共的取值方法,符合Java封装规范:
首先修改ImageLoadTask类代码,新增getUrl()方法:

public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;

    public ImageLoadTask(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    // 新增公共getter方法,外部可调用获取url属性
    public String getUrl() {
        return this.url;
    }

    // 原有doInBackground、onPostExecute逻辑保持不变
    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        imageView.setImageBitmap(result);
    }
}

修改后调用getter方法获取URL即可:

ImageView fff1 = (ImageView) findViewById(R.id.iop1);
TextView hol = (TextView) findViewById(R.id.mytext);
ImageLoadTask uu = new ImageLoadTask("https://maheshwaghela.com/VIPINIH/img/Mahesh/western/mimg10.jpg",fff1);
hol.setText(uu.getUrl());
uu.execute();

内容的提问来源于stack exchange,提问作者user2741987

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:15:04