Most of the time the Android system gives us a control that does not meet our needs and makes the interface a good one, so most of the controls are written by ourselves.
When I make a mass message interface, I need this adaptive sub-view number to change its own height of view so I wrote a control like this
Now share it and share it with everyone. Of course, if a friend has added some new features to download, please help to share the thank you.
We grow together.
Talk less about the code:
Mainactivity
public class Mainactivity extends actionbaractivity implements Onclicklistener{private Button button;private EditText Edit;private ScrollView scrollview;private myviewgroup myviewgroup;private Handler Handler; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initcontrol ();/** * Set Callback interface */myviewgroup.setmyviewgroupinterface (new Myviewgroupinterface () {@Overridepublic void Setscrollviewheight (int scrollviewheight,final boolean isadd) {//Set ScrollView height note scrollview The parent container is which layout below Layoutpara Ms should choose the corresponding//such as ScrollView's parent container is linearlayout, the following should be used//final linearlayout.layoutparams RL = ( Android.widget.LinearLayout.LayoutParams) Scrollview.getlayoutparams (); final relativelayout.layoutparams RL = ( Layoutparams) scrollview.getlayoutparams () Rl.height = Scrollviewheight;handler.post (new Runnable () {@ overridepublic void Run () {scrollview.setlayoutparams (RL); if (Isadd)//If it is added, position the location to the newly added child view Scrollview.scrollby ( 0, Myviewgroup.getgroupviewheight ());});}); /** * Initialize control */private void Initcontrol () {handler = new handler (); button = (button) This.findviewbyid (R.id.button); edit = ( EditText) This.findviewbyid (r.id.edit); ScrollView = (ScrollView) This.findviewbyid (r.id.scrollview); Myviewgroup = ( Myviewgroup) This.findviewbyid (R.id.myviewgroup); Button.setonclicklistener (this);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.button:string text = Edit.gettext (). toString (). Trim ( if (Textutils.isempty (text)) {Toast.maketext (this, "cannot be empty", Toast.length_short). Show (); break;} Addchildview (text); break;}} @SuppressLint ("Newapi") private void Addchildview (String text) {Final TextView TV = new TextView (this); Tv.settext (text); Tv.setsingleline (True); Tv.settextsize (typedvalue.complex_unit_sp,12); Tv.setmaxems (6); Tv.settextcolor ( Color.Black); Tv.setalpha (0.5f); int dp = DPTOPX.DIP2PX (this, 8); Tv.setpadding (DP,DP,DP,DP); Tv.setbackgroundresource (R.drawable.text_style); Tv.setonclicklistener (new OnclicklisteNER () {@Overridepublic void OnClick (View v) {myviewgroup.removeview (TV);//Click Delete}}); Myviewgroup.addview (TV, Myviewgroup.getchildcount ());//Add}}
Myviewgroup
public class Myviewgroup extends ViewGroup {public Myviewgroup (context context, AttributeSet attrs, int defstyle) {super (C Ontext, Attrs, Defstyle);} Public Myviewgroup (context context, AttributeSet Attrs) {Super (context, attrs);} Public Myviewgroup (Context context) {super (context);} public void Setmyviewgroupinterface (Myviewgroupinterface face) {this.face = face;} private int count;//The number of child view before changing private Boolean isadd; Determine whether to add or remove private myviewgroupinterface face;/** * Calculates the location of each child view */@Overrideprotected void OnLayout (Boolean changed, int l, int t, int r, int b) {//if (!changed)//Return;int i = Getchildcount (); if (count = = i) Return;isadd = True;if (count ; i)//change before the number of sub-view is greater than the current number of means to delete Isadd = False;count = i;int width = getmeasuredwidth (); int childwidth = 0;int Childheight = 0;int totalWidth = leftspacing + rightspacing;int currenttopposition = topspacing;int currentleftposition = leftSpacing;i NT MaxHeight = 0;for (int j = 0; J < i; J + +) {View v = getchildat (j); childwidth = V.getmeasuRedwidth (); childheight = V.getmeasuredheight (); if (j = = 0) {TotalWidth + = Childwidth;maxheight = Childheight;} else {total Width + = (childwidth + left_right_spacing), if (TotalWidth > width) {currenttopposition + = (maxheight + Top_bottom_spaci NG); currentleftposition = Leftspacing;maxheight = Childheight;totalwidth = leftspacing + rightspacing + childWidth;} else {if (Childheight > MaxHeight) {maxheight = Childheight;} View upchild = Getchildat (j-1); int upchildwidth = Upchild.getmeasuredwidth (); Currentleftposition + = (Upchildwidth + Left _right_spacing);}} L = currentleftposition;t = Currenttopposition;r = childwidth + currentleftposition;b = currenttopposition + childHeight;v . layout (l, T, R, b);} if (i = = 0) {if (face! = null) face.setscrollviewheight (0,ISADD);} Else{if (face = null) face.setscrollviewheight (SCROLLVIEWHEIGHT,ISADD);}} Private final int leftspacing = 10; Child view distance from left of parent container private final int rightspacing = 10;//child view distance from right of parent container private final int topspacing = 8;//Child view distance from top of parent container PR ivAte final int bottomspacing = 8;//child view distance from bottom of parent container private final int left_right_spacing = 10;//Two sub-view between left and right private final int top_bottom_spacing = 10;//Two sub-view interval between upper and lower private final int umberrows = 3;//The maximum number of rows in the parent container that can be channeling the view private int groupheight; private int Scrollviewheight;private int height,width;/** * Calculates the width/height of the parent container */@Overrideprotected void onmeasure (int Widthmeasur espec, int heightmeasurespec) {//obtains this ViewGroup superior container for its recommended width and height, and the calculation mode int widthmode = Measurespec.getmode (widthmeasurespec int heightmode = Measurespec.getmode (heightmeasurespec); int sizewidth = Measurespec.getsize (widthmeasurespec); int Sizeheight = Measurespec.getsize (HEIGHTMEASURESPEC);//Calculate all Childview width and height measurechildren (widthmeasurespec, HEIGHTMEASURESPEC); width = sizewidth;//viewgroup Width height = topspacing + bottomspacing;//viewgroup high int childCount = th Is.getchildcount ();//Total number of child view int childwidth = 0;//child view width int childheight = 0;//child view High int currentwidth = leftspacing + rightspacing;//the width int currentheight = 0;in added by the child viewT row = number of rows for 0;//child View for (int i = 0; i < ChildCount; i++) {View Childview = Getchildat (i); childwidth = Childview.getmeas Uredwidth (); childheight = Childview.getmeasuredheight (); if (i = = 0) {Row++;currentwidth + = Childwidth;currentheight = Childheight;} else {currentwidth + = (childwidth + left_right_spacing);} if (Currentwidth > width) {//When the child view is larger than the width of the parent container wrap and reset currentwidth and currentheightrow++;currentwidth = leftspacing + Rightspacing + childwidth;height + = (currentheight + top_bottom_spacing); currentheight = Childheight;} else {if (Childheight > Currentheight) {currentheight = Childheight;}} if (row <= umberrows) {scrollviewheight = height+ currentheight;}} Height + = Currentheight;groupheight = height; LOG.E ("", "scrollviewheight = =" +scrollviewheight); setmeasureddimension (width, height);} public int getgroupviewheight () {return groupheight;} @Overridepublic viewgroup.layoutparams generatelayoutparams (AttributeSet attrs) {New Marginlayoutparams (GetContext ( ), attrs); return SUPER.GEneratelayoutparams (attrs);} /** * Callback interface to change scrollview height * @author linxi * */public interface myviewgroupinterface{public void setscrollviewheight (int Scrollviewheight,boolean isadd);}}
Dptopx
public class Dptopx {/** * turns from DP units to px (pixels) */public static int dip2px (context context, float Dpvalue) based on phone resolution {final F Loat scale = Context.getresources (). Getdisplaymetrics (). Density;return (Int.) (Dpvalue * scale + 0.5f);} /** * According to the resolution of the phone from px (pixels) to the unit to the DP */public static int Px2dip (Context context,float pxvalue) {final float scale = CONTEXT.G Etresources (). Getdisplaymetrics (). Density;return (int) (Pxvalue/scale + 0.5f);} /** * Convert PX value to SP value, keep text size unchanged * * @param pxvalue * @param fontscale * (Properties in Displaymetrics class scaleddensity) * @return */public static int PX2SP (context context, float Pxvalue) {final float Fontscale = Context.getresources (). Getdisplaymetrics (). scaleddensity; return (int) (Pxvalue/fontscale + 0.5f); /** * Convert SP value to PX value, keep text size unchanged * * @param spvalue * @param fontscale * (displa Ymetrics Class Property scaleddensity) * @return */public static int sP2PX (context context, float Spvalue) {final float Fontscale = context.getresources (). Getdisplaymetrics (). Scaledd ensity; return (int) (Spvalue * fontscale + 0.5f); } }
Activity_main.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" match_parent "> <View Android:id= "@+id/v" android:layout_width= "fill_parent" android:layout_height= "1DP" Android:la yout_margintop= "10DP" android:background= "#FF2525"/> <scrollview android:id= "@+id/scrollview" Android:layout_width= "Fill_parent" android:layout_height= "0DP" android:layout_below= "@+id/v" Andro Id:layout_gravity= "center_vertical" android:layout_marginleft= "10DP" > <com.example.adaptivewidthheigh Tviewgroup. Myviewgroup android:id= "@+id/myviewgroup" android:layout_width= "Match_parent" Android:lay out_height= "Wrap_content" > </com.example.adaptivewidthheightviewgroup.MyViewGroup> </ScrollView> <view Android:layout_width= "Fill_parent" android:layout_height= "1DP" android:layout_below= "@+id/scrollview" android:backg round= "#195794"/> <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_con Tent "android:layout_alignparentbottom=" true "android:orientation=" vertical "android:paddingbottom=" 1 0DP "android:paddingtop=" 10DP "> <edittext android:id=" @+id/edit "android:layout _width= "Fill_parent" android:layout_height= "wrap_content" android:hint= "@string/input_content" Android:inputtype= "text" android:paddingbottom= "5DP" android:paddingleft= "10DP" and roid:paddingright= "10DP" android:paddingtop= "5DP" android:textcolor= "#000000" Android:tex Tsize= "18sp"/> <button android:id= "@+id/button" android:layout_width= "Wrap_content" Android:layout_height= "wrap_content" android:layout_gravity= "center" android:layout_margintop= "10DP" and roid:text= "@string/add" android:textcolor= "#000000" android:textsize= "18sp"/> </linearlayo Ut></relativelayout>
There is a need for the source of friends can write in the comments in the mailbox, see I will send you.
Android automatically typeset a viewgroup based on the number of child view inside