在ListView适配器中绘制之前设置ImageView的宽度和高度

时间:2013-05-29 21:49:23

标签: android android-listview android-imageview

我有ListView的适配器是ImageView的列表。我正在使用拉伸来使图像成为图像视图,因此我可以拍摄较小的图像并使其在屏幕上变大,但是ImageView通常只使用wrap_content这是一个问题,因为图像只是显示为正常的宽度和高度。有没有什么办法可以在绘制之前设置视图的高度和宽度,因为在这种情况下,我在绘制视图后无法控制视图。这是我的aapter方法:

  @Override
public View getView(int position, View convertView, ViewGroup parent) {
    String currentImage  = getItem(position);
    ScaleType scaleType = ScaleType.FIT_CENTER;
    float screenWidth = parent.getResources().getDisplayMetrics().widthPixels;

    if (convertView == null) {
        convertView = new ImageView(parent.getContext()); 
    }
  //         WHAT I WOULD LIKE TO BE ABLE TO DO, but this returns null pointer exception
 //     convertView.getLayoutParams().width = (int) screenWidth;
//      convertView.getLayoutParams().height = (int) ((float)(screenWidth/currentImage.getWidth())*currentImage.getHeight());

    ((ImageView) convertView).setScaleType(scaleType);
    ((ImageView) convertView).setImageBitmap(MainActivity.cache.getBitmap(currentImage));
    return convertView;
}

1 个答案:

答案 0 :(得分:0)

someView.setHeight() and someView.setWidth()之类的内容怎么样?还是someView.setLayoutParams()?您可以将其中任何一个添加到已覆盖的getView()回调中,它应该可以解决您的问题。

你也可以Create a Custom View覆盖像getMeasuredWidthAndState()这样的东西。 (我认为这是正确的方法之一,但我不是百分百肯定的。)您可以创建一个width类变量和一个height类变量,您的自定义ImageView的所有实例都将使用。但是,如果您只是想设置布局宽度和高度,那可能会有点多。