Cplusplusrookie 2016-02-12 06:29 采纳率: 50%
浏览 2475

android TextView中的setLayoutParam方法

各位前辈,我最近在自学安卓编程,碰到多次
setLayoutParams函数,我对这个函数的用法感觉很模棱两可,API中是这样写
Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.
我的理解是参数指定了这个调用这个方法中的组件在布局文件中的放置方式,但是如果用布局组件的addview方法,什么类型的布局组件调用这个方法,那么被加入的组件应该就是用该类型的布局方式就好了,为什么还要用setLayoutParams 其实我最不明白setLayoutParam中要传入的到底是什么参数??

  • 写回答

2条回答 默认 最新

  • 林深 2016-02-12 06:56
    关注

    这个就是指明view具有的布局性质,尤其是需要动态添加view的时候,不是通过layout拖进来,而是通过java代码创建view的时候,你想一下在layout里面如果不设置layout_width和layout_height会怎样,系统是不是会给你报错呀,因为你没有指定view的大小。而如果你是在自定义的情况下,系统也不会帮你创建layout_width和layout_height这类属性的,所以,这就需要通过setLayoutParam来进行设置
    比如说,你要在LinearLayout这个布局里面动态添加一个TextView,那么你在创建好之后必须要指定textView的LinearLayout.LayoutParams布局属性:

             TextView textView = new TextView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,100);
            textView.setLayoutParams(layoutParams);
            linearLayout.addView(textView);
    

    当然,如果你用的是RelativeLayout,那么就需要使用RelativeLayout.LayoutParams,不同的LayoutParams具有一些特定的不同的方法,要针对着来进行设置。

    评论

报告相同问题?

悬赏问题

  • ¥15 为什么eprime输出的数据会有缺失?
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题