方法:
setLayoutParams: 用来设置带有layout前缀的属性,所有子View attach到父View都会有LayoutParams,但是parentView.addView(childView)之前,childView.getLayoutParams()会返回null。
根据源码:
public void setLayoutParams(ViewGroup.LayoutParams params) { if (params == null) { throw new NullPointerException("Layout parameters cannot be null"); } mLayoutParams = params; resolveLayoutParams(); if (mParent instanceof ViewGroup) { ((ViewGroup) mParent).onSetLayoutParams(this, params); } requestLayout(); }
可以看出要想使setlayoutParams生效,必须有父View,就是调用了addView
setGravity:用来设置内部的子View。
代码:
mTitleBar = new LinearLayout(context); mTitleBar.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 200)); mTitleBar.setBackgroundColor(Color.BLACK); TextView textView = new TextView(context); textView.setText("lfjasodijfaodjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj"); mTitleBar.addView(textView); LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT); textView.setLayoutParams(textParams); textView.setGravity(Gravity.END); mBottomBar = new LinearLayout(context); TextView bottomTV = new TextView(context); bottomTV.setText("lfjasodijfaodjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj"); mBottomBar.addView(bottomTV); this.addView(mTitleBar); this.addView(mBottomBar); FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 70); frameLayoutParams.gravity = Gravity.TOP; mTitleBar.setLayoutParams(frameLayoutParams); FrameLayout.LayoutParams frameLayoutParams2 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 70); frameLayoutParams2.gravity = Gravity.BOTTOM; mBottomBar.setLayoutParams(frameLayoutParams2);
效果是:
两个TextView,在两个LinearLayout中,上面的TextView gravity是右边。两个LinearyLayout在FrameLayout中layout_gravity一个Top一个Bottom
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-04 03:28:35