我想创建一个ListView,其中每一行都有一个矩形图像和一些文本.像这样:
我的问题是某些图像的高度高于宽度,然后ListView看起来像这样:
这是我的实际代码:
xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:id="@+id/resultItem">
<ImageView
android:id="@+id/spicture"
android:layout_width="97dp"
android:layout_height="60dp"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:adjustViewBounds="true"
android:layout_marginTop="3dp" >
</ImageView>
<TextView
android:id="@+id/sname"
style="@android:style/TextAppearance.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
自定义适配器如下所示:
public class ListViewAdapter extends BaseAdapter {
private final Context mContext;
private ArrayList<Integer> imageId;
private ArrayList<String> textStr;
private final LayoutInflater inflater;
private static class ViewHolder {
ImageView imgView;
TextView txtView;
}
public ListViewAdapter(Context c) {
mContext = c;
inflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return imageId.size();
}
@Override
public Object getItem(int position) {
return textStr.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/**
* Rep per parametre un array amb els identificadors de les imatges i els
* string dels textes a mostrar
*
* @param idImages
* @param strText
*/
public void setData(ArrayList<String> strText, ArrayList<Integer> idImages) {
imageId = idImages;
textStr = strText;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.result_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.spicture);
holder.txtView = (TextView) convertView.findViewById(R.id.sname);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromResource(mContext.getResources(), imageId.get(position), 50, 50);
holder.imgView.setImageBitmap(bitmap);
holder.txtView.setText(textStr.get(position));
holder.txtView.setGravity(Gravity.CENTER);
return convertView;
}
}
如何将所有图像的矩形尺寸相同?
解决方法:
您可以在设置为listViewItem之前裁剪图像.或者您只使用相同比例的图像.
但我认为你正在寻找一个更简单的解决方案.只需添加scaleType =“centerCrop”
<ImageView
android:id="@+id/spicture"
android:scaleType="centerCrop"
android:layout_width="97dp"
android:layout_height="60dp"
android:layout_marginBottom="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:adjustViewBounds="true"
android:layout_marginTop="3dp" >
您可以在此处找到有关scaleTypes的更多信息:http://www.techrepublic.com/article/clear-up-ambiguity-about-android-image-view-scale-types-with-this-guide/
注意fitXY会缩放它以适应,但原始比率会丢失.