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

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 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?