I am having a fragment, in which i am inflating an item other than frgments view, which contains a linear layout. it is inflating fine, but now the problem is, when I am referring it, and trying to add a TextView programmatically in linear layout, it thorws an error. Any help will be preferable.
Error: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Fragment.java
public class ShortFrag extends Fragment{
ListView listview;
LinearLayout row1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.r_fragment, container, false);
listview=(ListView)view.findViewById(R.id.listview);
LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup) myinflater.inflate(R.layout.helper, listview, false);
row1= headerViewHolder.findViewById(R.id.linear);
TextView tv = getTextView(getTextView("button_one","button"));
//error here
row1.addView(tv);
return view;
}
private TextView getTextView(String text, String tag) {
TextView textView = new TextView(getActivity());
textView.setTextColor(ContextCompat.getColor(getActivity(), R.color.black));
textView.setTag(tag);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewPager.LayoutParams.WRAP_CONTENT
);
textView.setLayoutParams(params);
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setPadding(10, 5, 10, 5);
params.setMargins(10, 0, 10, 0);
return textView;
}
}
r_fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="vertical">
<Listview
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
helper.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"/>
</LinearLayout>
row1.addView(getTextView(getTextView("button_one","button")));- With the given code, that won't compile, and therefore could never throw that Exception. What's the actual code?TextView tv = getTextView(getTextView("button_one","button"));. You don't have agetTextView()method that can take aTextViewargument. I don't know what you did to fix that particular Exception.