今天在修改一个gridview的时候,发现里面的内容并不会自动适应,填满整个gridview,而是会产生滑动,尝试了很多的方法,包括在item文件中设定width和height,结果,宽度可调,高度却没办法调整,后来,在网上找了好多的方法,终于有了一个靠谱的,如下,也就是在item加载的adapter里面就行设置
@Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { if (MmsConfig.getIpMessagServiceId(mContext) == IpMessageServiceId.NO_SERVICE) { convertView = LayoutInflater.from(mContext).inflate(R.layout.share_grid_common_item, null); } else { convertView = LayoutInflater.from(mContext).inflate(R.layout.share_grid_item, null); } convertView.setTag(convertView); } else { convertView = (View) convertView.getTag(); } /* Vanzo:zhangshuli on: Wed, 21 Jan 2015 18:16:59 +0000 dime资源的引用方法
*/ int height = (int) mContext.getResources().getDimension(R.dimen.share_item_port_height); int width = (int) mContext.getResources().getDimension(R.dimen.share_item_port_width); AbsListView.LayoutParams param = new AbsListView.LayoutParams(width, height);//设置高和宽,注意是AbsListView
convertView.setLayoutParams(param); // End of Vanzo:zhangshuli TextView text = (TextView) convertView.findViewById(R.id.tv_share_name); ImageView img = (ImageView) convertView.findViewById(R.id.iv_share_icon); if (position < mStringArray.length) { text.setText(mStringArray[position]); img.setImageResource(mIconArray[position]); } return convertView; } }
调整gridview在父类中的位置,注意,是可以超出屏幕外边的哦
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childLeft = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { final int childWidth = childView.getMeasuredWidth(); /* Vanzo:zhangshuli on: Wed, 21 Jan 2015 18:12:28 +0000
这段代码就是设置gridview位置的,这个主要是相对父类的位置 */ int top = (int) mContext.getResources().getDimension(R.dimen.share_item_port_top); childView.layout(childLeft, top, childLeft + childWidth, childView.getMeasuredHeight()); // End of Vanzo: zhangshuli childLeft += childWidth; } } }
附上代码中处理dp跟px转化的方法
一个就是在dimen.xml中定义,引用的时候会自动转化为px;
另一个就是直接在代码中将一个固定数值转化为px,如下
public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } TextView text = (TextView) convertView.findViewById(R.id.tv_share_name);