我遇到了错误:
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);
我的代码有什么问题吗?
答案 0 :(得分:0)
尝试更换:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.parentLayout);
使用:
RelativeLayout rl = new RelativeLayout(this);
您现有的代码使用现有的RelativeLayout,而这个代码使用新的代码。如果您想使用现有的,则必须先调用removeAllViews()
清空它。
答案 1 :(得分:0)
您的根布局是相对布局。将textview添加到相对布局。您需要首先将布局的内容设置为您的活动,然后初始化相对布局。然后,您可以将视图添加到相对布局。
注意:您可以查找当前视图层次结构设置为活动的ViewById。因此,您需要先将布局设置为活动,然后初始化相对布局
尝试以下
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的建议和相同的视图创建一个relativelayout。
答案 2 :(得分: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);