我有6张可绘图像。我把这些图像放在一个2x3的GridView中,如果它是portraite,如果它是横向的,则放置3x2,但我有一个问题:如果我尝试根据parent.getMeasuredWidth()和parent.getMeasuredHeight();
进行测量来自日志:
代码 ImageAdapter :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {mContext = c;}
public int getCount() {return mThumbIds.length;}
public Object getItem(int position) {return null;}
public long getItemId(int position) {return 0;}
public View getView(int position, View convertView, final ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
int width = parent.getMeasuredWidth();
int height = parent.getMeasuredHeight();
int orientation = parent.getResources().getConfiguration().orientation;
int vh,vo;
if(orientation == 1){
vh = width/2;
vo = height/3;
} else {
vh = (width/3);
vo = (height/2);
}
Log.e(TAG,"w: "+vh+" h:"+vo);
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(vh, vo));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.gradient_bg_t1,
R.drawable.gradient_bg_t2,
R.drawable.gradient_bg_t4,
R.drawable.gradient_bg_t5,
R.drawable.gradient_bg_t6,
R.drawable.gradient_bg_t3
};
}
代码 MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
谢谢。
答案 0 :(得分:0)
它返回零,因为父视图尚未绘制。您可以将代码发布到父视图,以便在绘制父视图后运行。
使用以下代码:
parent.post(new Runnable() {
@Override
public void run() {
int w = parent.getMeasuredWidth();
int h = parent.getMeasuredHeight();
...
}
});
答案 1 :(得分:0)
我已经在ImageAdapter中尝试过@Amir Ziarati的代码(在StackOverflow中找到它),但我无法将值超出范围。
我喝了一点咖啡后,我改变了代码: 我在ImageAdapter 2中创建了新的int变量 w,h 的宽度和高度:
private Context mContext;
private int w,h;
public ImageAdapter(Context c,int width,int height) {
mContext = c;
w = width;
h = height;
}
并在MainActivity中:
gridview = (GridView) findViewById(R.id.gridview);
gridview.post(new Runnable() {
@Override
public void run() {
int w = gridview.getMeasuredWidth();
int h = gridview.getMeasuredHeight();
gridview.setAdapter(new ImageAdapter(MainActivity.this,w,h));
}
});
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
它正在发挥作用。