動態新增控制元件導致weight和height失效的解決方法
阿新 • • 發佈:2019-02-20
1 /** 2 * <p>Adds a child view. If no layout parameters are already set on the child, the 3 * default parameters for this ViewGroup are set on the child.</p> 4 * 5 * <p><strong>Note:</strong> do not invoke this method from 6 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 7 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 8 * 9 * @param child the child view to add 10 * 11 * @see #generateDefaultLayoutParams() 12 */ 13 public void addView(View child) { 14 addView(child, -1); 15 } 16 17 public void addView(View child, int index) { 18 if (child == null) { 19 throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup"); 20 } 21 LayoutParams params = child.getLayoutParams(); 22 if (params == null) { 23 params = generateDefaultLayoutParams(); 24 if (params == null) { 25 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 26 } 27 } 28 addView(child, index, params); 29 } 30 31 protected LayoutParams generateDefaultLayoutParams() { 32 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 33 }