Reputation: 1865
I am trying to inflate a EditText
view inside a RelativeLayout
in my Activity
.
But getting an error says:
The specified child already has a parent. You must call removeView() on the child's parent first.
My code:
RelativeLayout relLayout= new RelativeLayout(insideActivity);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relLayout.setLayoutParams(params);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.holo_edit_text, null);
EditText searchBox = (EditText)view.findViewById(R.id.holo_text);
relLayout.addView(searchBox);
And here is holo_edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/holo_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
</RelativeLayout>
Upvotes: 1
Views: 2312
Reputation: 1865
I have fixed my issue by simply setting the LayoutParams to searchBox before adding it to the RelativeLayout. And its working fine.
Thanks all for your response.
Upvotes: 0
Reputation: 886
Use a try/catch mechanism.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView != null) {
((ViewGroup) rootView.getParent()).removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.your_layout_file_here, container,false);
EditText searchBox = (EditText)rootView.findViewById(R.id.holo_text);
relLayout.addView(searchBox);
} catch (InflateException e) {
}
return rootView;
}
Upvotes: 0
Reputation: 2555
your holo_edit_text.xml should be
<?xml version="1.0" encoding="utf-8"?>
<EditText
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/holo_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
/>
And the way you add it to the view should be like this
EDIT (use getLayoutInflater() instead)
View view = getLayoutInflater().inflate(R.layout.holo_edit_text, null);
//EditText searchBox = (EditText)view.findViewById(R.id.holo_text);
//The last sentence is not neccesary
relLayout.addView(view);
Have you tried this while adding to relative layout
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
relLayout.addView(view, params);
Upvotes: 1
Reputation: 24853
Try this..
View child_view = LayoutInflater.from(this).inflate(R.layout.holo_edit_text, null);
relLayout.addView(child_view);
Upvotes: 0