记录几点有关LayoutParams的知识
1. LayoutParams是ViewGroup中的一个内部类,用来描述子View在ViewGroup中的位置,宽高信息。
2.其他继承ViewGroup的类基本上都重新写了LayoutParams这个内部类,但是每一个继承的却是ViewGroup中的MarginLayoutParams。
3. 在调用view的setLayoutParams方法设置layoutParams时,其中的LayoutParams要传其父View的LayoutParams类型,因为我们是要在父布局中描述view的位置及宽高占多少。
1. LayoutParams是ViewGroup中的一个内部类,用来描述子View在ViewGroup中的位置,宽高信息。
2.其他继承ViewGroup的类基本上都重新写了LayoutParams这个内部类,但是每一个继承的却是ViewGroup中的MarginLayoutParams。
3. 在调用view的setLayoutParams方法设置layoutParams时,其中的LayoutParams要传其父View的LayoutParams类型,因为我们是要在父布局中描述view的位置及宽高占多少。
注:关于第3点多说一点,如果你的view是写在XML文件中,不是用代码自动生成的,在使用setLayoutParams(LayoutParams params)方法改变view在父view中的布局时,参数必须传其父view的LayoutParams类型,比如父view是LinearLayout,那个就需传LinearLayout.LayoutParams类型,否则会报错。反之,如果view是使用代码动态生成的,那么就可以传父view的LayoutParams, 也可以穿其父view的父类中的LayoutParams,在addView的方法内部会自动转换,但是建议如果明确知道父view是谁,就传父view的LayoutParams。
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/id_liear"
android:layout_width="120dp"
android:layout_height="120dp"
android:background="@android:color/holo_blue_light">
<TextView
android:id="@+id/id_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"
android:text="world"/>
</LinearLayout>
代码:
mLayout = (LinearLayout) findViewById(R.id.id_liear);
mTextView = (TextView) findViewById(R.id.id_textview);
//ViewGroup.LayoutParams vlp = new ViewGroup.LayoutParams(120, 120);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(70, 70);
//mTextView.setLayoutParams(vlp);//使用ViewGroup的LayoutParams会报错,因为TextView的父View是LinearLayout
mTextView.setLayoutParams(llp); //改变TextView的布局