我想在我的应用程序中获取GridView项目大小。我只知道我可以在回调中获得项目大小:
private class GridViewItemSelectedListener implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
int viewh = view.getHeight();
int vieww = view.getWidth();
Log.d(TAG, view.getWidth() + "," + view.getHeight() +
" > position:(" +view.getX() + " , " + view.getY() + ")");
}
}
但我无法在onResume中获取其项目大小,即使我在处理程序中尝试过:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
case UPDATE_GRIDVIEW:
View itemView = mGridView.getChildAt(0); //this will return null pointer;
final FrameLayout.LayoutParams lp= new FrameLayout.LayoutParams(itemView.getLayoutParams());
lp.setMargins( -3, 0, 0, 0);
selectorView.setLayoutParams(lp);
break;
default:
break;
}
}
};
我在onResume方法
中触发了处理程序@Override
protected void onResume() {
Message msg = new Message();
msg.what = UPDATE_GRIDVIEW;
mHandler.sendMessage(msg);
super.onResume();
}
我甚至试图调用GridView的方法getSelectedItem()等...,也无法做到。你能给我一些建议吗,原因是什么?以及如何获得gridview项目大小?
答案 0 :(得分:0)
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchMode="columnWidth" />
所以我们只需要拉伸行。我们可以做的,通过计算当我们知道GridView和rowsCount的高度时应该有多少rowHeight。
public class YourAdapter extends BaseAdapter {
int rowsCount;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = layoutInflater.inflate(R.layout.item_view, parent, false);
int height = parent.getHeight();
if (height > 0) {
LayoutParams layoutParams = itemView.getLayoutParams();
layoutParams.height = (int) (height / rowsCount);
} // for the 1st item parent.getHeight() is not calculated yet
}
}