gpt4 book ai didi

android - 程序化 ImageView 和 picasso

转载 作者:行者123 更新时间:2023-12-02 03:23:28 30 4
gpt4 key购买 nike

我是 Android 开发的新手,但遇到以下问题。我正在尝试以编程方式创建多个 ImageView 并使用 Picasso 加载图像,但我无意中发现了以下问题。

编辑:我想要实现的是我希望使用 width=FILL_PARENT 和 height=WRAP_CONTENT 创建 ImageView

请参阅下面的代码摘录:

此示例有效但不是我想要的(加载图像)

LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
ImageView articleTitleImageView = (ImageView) findViewById(R.id.articleTitleImageView);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300,300);
params.gravity= Gravity.CENTER_HORIZONTAL;
[...]
ImageView iv = new ImageView(this);
setImage(iv, imageURL);
articleBodyLL.addView(iv, params);
[...]
private void setImage(final ImageView imageView, final String imgURL) {
Picasso.with(ArticleProvider.getContext())
.load(imgURL)
.fit().centerCrop()
.error(R.drawable.default_image)
.into(imageView);
}

此示例不起作用(未显示图像)

LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
ImageView articleTitleImageView = (ImageView) findViewById(R.id.articleTitleImageView);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity= Gravity.CENTER_HORIZONTAL;
[...]
ImageView iv = new ImageView(this);
setImage(iv, imageURL);
articleBodyLL.addView(iv, params);
[...]
private void setImage(final ImageView imageView, final String imgURL) {
Picasso.with(ArticleProvider.getContext())
.load(imgURL)
.fit().centerCrop()
.error(R.drawable.default_image)
.into(imageView);
}

最佳答案

看看这段代码。这很好用。一个建议是,如果您正在尝试形成某种列表,请查看 RecyclerView。避免异常(许多异常:p)。

LinearLayout articleBodyLL = (LinearLayout) findViewById(R.id.articleBody);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity= Gravity.CENTER_HORIZONTAL;
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
setImage(iv, "http://square.github.io/picasso/static/sample.png");
articleBodyLL.addView(iv, params);

//////////////////////////////////////////////
private void setImage(final ImageView imageView, final String imgURL) {
Picasso.with(this)
.load(imgURL)
.error(R.mipmap.ic_launcher)
.into(new Target() {
@Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.e("loaded", "onBitmapLoaded: loaded" );
imageView.setImageBitmap(bitmap);
imageView.invalidate();
}

@Override public void onBitmapFailed(Drawable errorDrawable) {
Log.e("loaded", "onBitmapFailed: load failed" );
}

@Override public void onPrepareLoad(Drawable placeHolderDrawable) {

}
});
}

关于android - 程序化 ImageView 和 picasso ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663209/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com