我有一个循环来向RelativeLayout添加可变数量的视图,我想设置一些规则,例如BELOW
,我的问题是我使用标签动态命名对象,并使用addRule()
我需要使用id的方法,所以我尝试的是在每次运行循环时设置一个 Id,这不是第一次。
这是我的代码:
for(int i = 1; i <= kNumberofViews; i++){
View = new MyView(context);
RelativeLayout.LayoutParams params = new LayoutParams(kViewWidth, kViewHeight);
params.setMargins(kMarginLeft, kMarginTop, kMarginRight, kMarginBottom);
params.addRule(CENTER_HORIZONTAL);
if (i != 1){
MyView view = (MyView)view.findViewWithTag(i-1);
view.setId(i);
params.addRule(RelativeLayout.BELOW, view.getId());
}
View.setTag(i);
View.setBackgroundColor(Color.GREEN);
System.out.println("View " + i +" added correctly");
addView(View, params);
}
我该如何解决?
编辑:
05-18 14:57:19.549: E/AndroidRuntime(5500): FATAL EXCEPTION: main
05-18 14:57:19.549: E/AndroidRuntime(5500): java.lang.RuntimeException: Unable to start activity ComponentInfo{me.gabrielesteban.app/me.gabrielesteban.app.MyRelativeLayoutTest}: android.view.InflateException: Binary XML file line #7: Error inflating class me.gabrielesteban.app.GD.MyRelativeLayout
05-18 14:57:19.549: E/AndroidRuntime(5500): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
05-18 14:57:19.549: E/AndroidRuntime(5500): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)
05-18 14:57:19.549: E/AndroidRuntime(5500): at android.app.ActivityThread.access$600(ActivityThread.java:153)
编辑2:
我认为问题出在下面一行MyView view = (MyView)view.findViewWithTag(i-1);
,这行正确吗?