【发布时间】:2017-02-28 15:48:50
【问题描述】:
我正在创建一个适配器,它应该使用汽车图像和模型名称填充 GridView。我创建了一个网格项目作为自己的 XML 文件,并带有所需的小部件(ImageView 和 TextView)。但是,我似乎无法从我的 CarsGridViewItem 实例中放大视图。但是,如果我从适配器的 getView-method 扩展视图,它会起作用。
如果我从CarsGridViewItem 实例中膨胀视图会发生什么,我看不到应该膨胀的视图。
下面是我的CarsGridViewItem类
public class CarsGridViewItem extends RelativeLayout {
private Car car;
private ImageView carImg;
private TextView nameTxt;
public CarsGridViewItem(Car car, Context context) {
super(context);
this.car = car;
inflate(getContext(), R.layout.fragment_cars_grid_item, this);
findViews();
setupViews();
}
private void findViews() {
this.carImg = (ImageView)findViewById(R.id.car_image);
this.nameTxt = (TextView)findViewById(R.id.car_name);
}
private void setupViews(){
this.car.loadImageIntoView(this.carImg);
this.nameTxt.setText(this.car.getName());
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
@Override
protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
}
}
还有我的适配器的getView-方法
public View getView(int position, View convertView, ViewGroup parent){
return new CarsGridViewItem(cars.get(position), mContext);
/* The code below works!
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.fragment_cars_grid_item, null);
ImageView carImg = (ImageView)view.findViewById(R.id.car_image);
cars.get(position).loadImageIntoView(carImg);
TextView nameTxt = (TextView)view.findViewById(R.id.car_name);
nameTxt.setText(cars.get(position).getName());
return view;*/
}
我在这里做错了,但我似乎无法弄清楚是什么。我发现的所有关于膨胀视图主题的例子都是这样的!
【问题讨论】:
-
您可以调试并查看视图的布局方式。
Show layout bounds或Tools-> Android -> Layout Inspector。在我看来,您的视图高度为 0。 -
布局检查器的重要提示。这告诉我
CarsGridViewItem有宽度和高度,而其中的膨胀的RelativeLayout 没有宽度和高度!这可能是什么原因造成的? -
也发布
CarsGridViewItemclass。 -
@azizbekian 更新了整个
CarsGridViewItem类
标签: java android android-layout android-view layout-inflater