在achat项目中,对话内容的长宽设置为自适应,但是如果文本内容太多,则宽度差不多布满,若自己说的和对方说的都很多内容,则满屏都是文字,则不容易分辨出是来自别人说的还是自己说的。那么需要对本身具有自适应的布局再来个宽度限制。
首先,在xml里面定义layout的layout_width/layout_height都要设置为wrap_content,然后在getView方法里面,一开始就让这个布局wrap_content(为什么xml里面设置了wrap_content,这里还要再设置一遍呢?因为布局的重用,不多说了),WidgetController.setLayoutWidth(holder.lay_content, MarginLayoutParams.WRAP_CONTENT);
然后,在填充完布局后,再来一段,让这个布局不能超过屏幕宽的50%,若超过则以这个为最大宽度:
int w=(int)(DensityUtil.getScreenWidth()*0.5); if (WidgetController.getWidth(holder.lay_content)>w){ WidgetController.setLayoutWidth(holder.lay_content,w); }
下面是setLayoutWidth方法的代码,相当好用:
/** * 設置View的寬度(像素),若設置爲自適應則應該傳入MarginLayoutParams.WRAP_CONTENT * @param view * @param width */ public static void setLayoutWidth(View view,int width) { /* MarginLayoutParams margin=new MarginLayoutParams(view.getLayoutParams()); margin.setMargins(margin.leftMargin,y, margin.rightMargin, y+margin.height); //RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin); //view.setLayoutParams(layoutParams); ViewGroup.MarginLayoutParams layoutParams =newLayParms(view, margin); //RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(margin); view.setLayoutParams(layoutParams); view.requestLayout();*/ if (view.getParent() instanceof FrameLayout){ FrameLayout.LayoutParams lp=(FrameLayout.LayoutParams) view.getLayoutParams(); lp.width=width; view.setLayoutParams(lp); //view.setX(x); view.requestLayout(); } else if (view.getParent() instanceof RelativeLayout){ RelativeLayout.LayoutParams lp=(RelativeLayout.LayoutParams)view.getLayoutParams(); lp.width=width; view.setLayoutParams(lp); //view.setX(x); view.requestLayout(); } else if (view.getParent() instanceof LinearLayout){ LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)view.getLayoutParams(); lp.width=width; view.setLayoutParams(lp); //view.setX(x); view.requestLayout(); } }
转载请注明出处: http://blog.csdn.net/rocklee