我收到此错误: java.lang.IllegalStateException:指定的子级已有父级。您必须先在孩子的父母身上调用removeView()。
XML文件名是 panchang_cal_inflate
这是我的代码:
public class PanchangCal extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_panchang_cal);
LinearLayout linearday=(LinearLayout)findViewById(R.id.sun2);
LinearLayout linearday1=(LinearLayout)findViewById(R.id.sun20);
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.activity_panchang_cal_inflate, null);
linearday1.addView(myView);
linearday.addView(myView);
}
}
答案 0 :(得分:0)
您确定要将myView
添加为linearday1
和linearday
的子视图吗?因为那不会像这样工作。
如果你想这样做,你必须两次夸大布局:
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView1 = inflater.inflate(R.layout.activity_panchang_cal_inflate, null);
View myView2 = inflater.inflate(R.layout.activity_panchang_cal_inflate, null);
linearday1.addView(myView1);
linearday.addView(myView2);
但是,我确实认为您确实要将linearday1
和linearday
添加为myView
的子视图 - 我错了吗?
myView.addView(linearday1);
myView.addView(linearday);
修改强> 如果你想使用30次以上的代码,你可以使用这样的循环:
View[] linearday = new View[30];
/** Save your linearday layouts in this array **/
LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 30; i++) {
View myView inflater.inflate(R.layout.activity_panchang_cal_inflate, null);
linearday[i].addView(myView);
}
对于第二个代码块,它非常相似:
View[] linearday = new View[30];
/** Save your linearday layouts in this array **/
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView inflater.inflate(R.layout.activity_panchang_cal_inflate, null);
for (int i = 0; i < 30; i++) {
myView.addView(linearday[i]);
}
编辑2:
根据评论中的要求,当您的视图存储在XML文件中时,您需要有关阵列填充过程的更多详细信息:
有两种方法可以实现这一目标。如果你的布局在XML文件中有完全随机的ID,那么你必须这样做:
View[] linearday = new View[30];
linearday[0] = findViewById(R.id.linearday_hello);
linearday[1] = findViewById(R.id.linearday_window);
linearday[2] = findViewById(R.id.linearday_test);
// ... and so on
但是,如果他们有一个共同的模式,只有一个增加的索引(例如linearday0
,linearday1
,linearday2
),那么你可以像这样缩短代码:
View[] linearday = new View[30];
for (int i = 0; i < 30; i++) {
int resid = getResources().getIdentifier("linearday" + i, "id", getPackageName());
linearday[i] = findViewById(resid);
}