比如在XML里面定义了一个framelayout ,如果在代码而不是xml里面添加VIEW,怎样设置它的位置呢?用layout方法好像不管用?

解决方案 »

  1.   

    首先你要得到这个 frameLayout 一般是通过 findViewById然后用 他的addView方法
      

  2.   

    把你的Layout用layoutinf...拿出来,调用 它的一个方法叫作layout.addview(view,layoutparam);第二个参数就是它的布局中的设置。我给你上贴一些自己写的布局吧,这样可能比较清醒:rp = new RelativeLayout.LayoutParams(layout_width / 3 - 1,
    layout_height / 2 - 1);
    rp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
    RelativeLayout.TRUE);
    rp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
    RelativeLayout.TRUE);
    this.addView(views.get(2), rp);这样可能比较明白一点,我用的是relativelayout
      

  3.   


    不要用findViewById()这个方法拿到的是view而不是viewGroupLayoutInflater inflater = (LayoutInflater) this.context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.search_result, null);
    我喜欢用这种方式拿
      

  4.   

    public View inflate (int resource, ViewGroup root) 
    Since: API Level 1 
    Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.Parameters
    resource  ID for an XML layout resource to load (e.g., R.layout.main_page) 
    root  Optional view to be the parent of the generated hierarchy. Returns
    The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file. 
    这个东西的返回值也是一个View ,还是要通过向下强制转型有简单的findViewById为什么不用。
      

  5.   

    也对,这个与findviewlayout不同的地方在于inflate可以读取文件而不是IDfindViewbyId是根据ID拿布局。二楼的对不住了。
      

  6.   


    findViewById需要在setContentView之后才能取到inflate可以不setContentView就拿到其实这个地方其实我很矛盾,也很纠结。如果我需要用inflate去拿xml的布局,那我肯定要加载他,不然我写到XML去干什么,所以findViewById就更方便。但是如果我不想用XML的话,我直接全动态生成布局,再给setContentView所以。。
      

  7.   


    谢谢,你的方法很给力~,那如果用frameLayout 怎么进行定位呢?
      

  8.   

    frameLayout
    没有用过说不好,也不好说。但是我相信是一样的。FrameLayout.LayoutParams这个类中提供了你想要的所有布局参数,只须要设置一下,然后addview()方法中增加进去就可以了
      

  9.   

    really,回去看看。先谢谢了。
      

  10.   

    FrameLayout.LayoutParams里面只有三个参数啊,怎么定位?
    我在描述一下问题
    1,比如我自定义一个CustomView 继承了 FrameLayout
    2,我再定义一个CustomViews 继承了ViewGroup
    3,我想在viewGroup 里面布置CustomView用代码布局,不用XML文件,如何操作,谢谢各位?
      

  11.   

    addView方法怎么定位,比如我定位到 左50px ,顶50px
      

  12.   


    先把他add到布局,然后用他自己的layout摆过去
      

  13.   

    换个思路,如果你在XML中会怎么作?我是这样作的:
    用一个相对布局添加view设置它与左上的间距。
    添加方法一样。
    然后再将这个相对布局添加到你的FrameLayout在添加relativelayout时
    是不是需要设置参数就要看你的须要了。