为什么我的编程设置相对布局位置没有正常工作?

时间:2014-03-07 16:08:35

标签: android relativelayout

我想要一个像这样的3x3网格视图:

0 1 2
3 4 5
6 7 8

所以我使用了以下代码:

for (int i=0; i<9; i++) {
        View ns = (View)View.inflate(ctx, R.layout.view_layout, null);
        viewArray.add(ns);
        ns.setId(i);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        if (i>2) {
            if (i<6) {
                lp.addRule(RelativeLayout.BELOW, viewArray.get(1).getId());
            }
            else {
                lp.addRule(RelativeLayout.BELOW, viewArray.get(3).getId());
            }
        }
        if (i%3!=0) {
            lp.addRule(RelativeLayout.RIGHT_OF, viewArray.get(viewArray.size()-2).getId());
        }


        //This shouldn't be necessary, but it is
        if (i==3) {
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.RIGHT_OF, viewArray.get(3).getId());
            viewArray.get(1).setLayoutParams(lp1);
        }


        addView(ns, lp);

    }

此代码目前可以正常工作,但仅限于“if(i == 3)”部分。没有它,1与0重叠(因此RIGHT_OF无法正常工作)。知道问题是什么吗?

0 个答案:

没有答案