微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android-在布局中多次添加自定义视图

我有一个自定义XML文件.我想在布局中(相对而言)重复n次(动态地(显然)).

我看过很多帖子,但没有帮助.我不是在寻找ListView或Adapters左右.就像-A RelativeLayout一样简单.在其中,在其上添加自定义XML.任何次数.

使用静态LinearLayout(垂直方向)时,动态添加视图会导致一次渲染,而不是一个视图另一个视图.不知道为什么.尽管TextView左右在LinearLayout(垂直)内部的循环中确实要在另一个下方重复一个.

然后,我动态创建了布局(相对),并扩展了自定义XML.显示一个.当我在第一个下尝试另一个时,它告诉我先删除孩子的父母(例外).如果我这样做并再次添加,则与删除一个渲染视图并再次添加一样好.

那么,如何在同一布局中获得多个视图?

我尝试过的粗略介绍:

 mainLayout = (RelativeLayout)findViewById(R.id.mainlay); //Mainlayout containing some views already

        params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW,R.id.sideLayout); //sideLayout is an existing LinearLayout within the main layout.



        View child = getLayoutInflater().inflate(R.layout.dynamiccustomlayout,null);

        RelativeLayout r1 = new RelativeLayout(this);

        r1.setLayoutParams(params);
        r1.addView(child);
        mainLayout.addView(r1);
        mainLayout.setLayoutParams(params);
        mainLayout.addView( child);
       /* r2 = new RelativeLayout(this);
        r2.setLayoutParams(params);
        r2.addView(contentLayout); [Gives exception] */ 

解决方法:

这就是我的工作方式…

在此之前,android的问题是:

如果在LinearLayout(水平)内部添加动态视图,则它们将与新创建的实例一起水平显示,并添加到视图中.

但是,令人震惊的是,在LinearLayout(垂直方向)的情况下,情况并不相同.因此整个混乱.

解:

RelativeLayout布局文件已与变量绑定,如下所示:

customLay = (RelativeLayout) mainLay.findViewById(R.id.dynamicCustomLayout);

然后,创建一个动态RelativeLayout,在其中添加/包装前一个变量.

customLayout = new RelativeLayout(this);
customLayout.addView(customLay);

每个布局都有一个ID:

 customLayout.setId(i);

然后运行循环(如果i = 0且i> 0的条件为2)

对于i> 0(表示第二个动态布局,要添加到第一个下面),将创建LayoutParameter:

params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

然后对于i> 0,使用动态视图的ID,将它们一个添加到另一个下面:

//Following code below used id to place these views below each other to attain list type arrangement of views//

    // i==0 for first view on top//
     if (i == 0) { 
                        params.addRule(RelativeLayout.BELOW, R.id.sideLayout);
                        customLayout.setLayoutParams(params);
                    } 
   // i>0 for views that will follow the first top//
else { 
                        params.addRule(RelativeLayout.BELOW, i - 1);
                        customLayout.setLayoutParams(params);
                    }

然后添加到主根布局,其中需要显示所有这些视图或卡片:

includeLayout.addView(customLayout);

当然,代码不只是这个.我写了一些重要的观点,这些观点可以帮助我实现目标,并可能在将来帮助其他人.

所以主要的本质是-

>使用动态RelativeLayout,
>绑定静态RelativeLayout,然后
>为动态RelativeLayout包装器分配ID,并
>根据ID使用RelativeLayoutParameters放置以下内容
低于先前ID的ID.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐