0

我对错误感到震惊:

java.lang.IllegalStateException: The specified child already has a parent. You must 
call removeView() on the child's parent first.

单击发送按钮时,我想创建相对布局。

RelativeLayout rl = (RelativeLayout) findViewById(R.id.parentLayout);                                        
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//layoutParams.setMargins(0, 0, 25, 0);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT,
    RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
TextView tv= new TextView(ChatWithFriend.this);
tv.setId(layId);
tv.setText("data");
tv.setLayoutParams(lp);
rl.addView(tv);
setContentView(rl, layoutParams);

我的代码有什么问题吗?

4

3 回答 3

0

尝试更换:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.parentLayout); 

和:

RelativeLayout rl = new RelativeLayout(this);

您现有的代码使用现有的 RelativeLayout,而这个代码使用了一个新的。如果要使用现有的,则必须先调用removeAllViews()以清空它。

于 2013-06-11T05:37:25.283 回答
0

您的根布局是相对布局。将 textview 添加到相对布局。您需要先将布局的内容设置为您的活动,然后再初始化相关布局。然后您可以将您的视图添加到相对布局中。

注意:您可以findViewById 设置为活动的当前视图层次结构。所以你需要先给activity设置布局,然后再初始化你的相对布局

试试下面

setContentView(R.layout.mylayout);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.parentView);                                        
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//layoutParams.setMargins(0, 0, 25, 0);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
TextView tv= new TextView(ChatWithFriend.this);
tv.setId(layId));
tv.setText("data");
tv.setLayoutParams(lp);
rl.addView(tv,layoutParams);

或者,您可以按照 Raghav Sood 的建议创建一个相对布局,并创建相同的视图。

于 2013-06-11T05:45:32.557 回答
0

尝试以下代码

setContentView(R.layout.your_xml);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.parentLayout);                                        
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
TextView tv= new TextView(ChatWithFriend.this);
tv.setId(layId);
tv.setText("data");
tv.setLayoutParams(lp);
rl.addView(tv,lp);
于 2013-06-11T05:46:14.310 回答