我正在动态扩展布局。我想在该布局中添加子视图。我试图补充这一点,但得到了例外:
java.lang.IllegalStateException:指定的子级已经有父级。必须首先对孩子的父级调用removeView()
事件函数:
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
TextView showLocation = (TextView)eventView.findViewById(R.id.At);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
if (showLocation.getParent() != null)
((ViewGroup) showLocation.getParent()).removeView(showLocation);
showLocation.setText(location);
if(location == null)
{
showLocation.setVisibility(View.INVISIBLE);
}
else {
showLocation.setVisibility(View.VISIBLE);
}
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
dayplanView.addView(showLocation);
container.addView(tvTitle);
container.addView(showLocation);
eventView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
事件视图布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape"
android:layout_marginLeft="60dp"
android:id="@+id/container"
android:layout_marginRight="12dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/textViewTitle"
android:layout_marginLeft="10dp"
android:textColor="@android:color/white"
android:layout_marginTop="01dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/At"
android:layout_below="@+id/textViewTitle"
android:layout_toEndOf="@+id/textViewTitle"
android:layout_marginTop="01dp"
android:text="At : "
android:textColor="@android:color/white" />
</RelativeLayout>
</RelativeLayout>
container.addView(showLocation)出现异常;
我对标题也有同样的例外,所以我这样做了:
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
所以问题解决了。但现在我想在视图中添加另一个文本视图。它再次出现同样的错误,我试图以同样的方式删除此视图。
如果(showLocation.getParent()!=空)
((ViewGroup)showLocation.getParent()).removeView(showLocation);
仍有例外。
怎么了。?