关于Android LayoutParams的总结

记录几点有关LayoutParams的知识
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的布局







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值