我有一个循环来向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);
中,这条线是否正确?
答案 0 :(得分:1)
在分配新ID之前,请尝试检查是否分配了ID!
for(int i = 1; i <= kNumberofViews; i++){
View v = 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)findViewWithTag(i-1);
if (view.getId() == View.NO_ID)
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);
}
修改强>
已编辑,选中了documentation并且您是对的,视图不能为空,但如果没有分配视图,则返回的值为View.NO_ID(或-1)。
答案 1 :(得分:1)
我再次回顾了我的代码,并且我也阅读了How do I call findViewWithTag in the OnCreate() method of an activity?,我看到当我调用findViewWithTag()方法时,在方法之前放置了我找到的相同对象,因此结果是使用该标记在该对象中找到一个对象,所以我唯一需要做的就是删除该部分。
MyView view = (MyView)view.findViewWithTag(i-1); //Bad way to find the View
MyView view = (MyView)findViewWithTag(i-1); //Good way to find the View by tag