How can I clone the properties of specific a view in the layout?
I have this view
<com.google.android.material.textview.MaterialTextView
android:id="@ id/fragment_login_main_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="25dp"
android:fontFamily="@font/font_en_medium"
android:gravity="center"
android:text="@string/fragment_login_main_text"
android:textColor="@color/fragment_login_text1_main_text"
android:textSize="22.5sp" />
I want to create a clone of this view and I did it like that
MaterialTextView materialTextView = fragmentLoginBinding.fragmentLoginMainText;
materialTextView.setId(View.NO_ID);
fragmentLoginBinding.getRoot().addView(materialTextView);
But I got this error
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
So I want to know is there any way to create a clone from that view without doing it manually like this
MaterialTextView materialTextView = new MaterialTextView(requireActivity());
materialTextView.setText(fragmentLoginBinding.fragmentLoginMainText.getText());
materialTextView.setTypeface(fragmentLoginBinding.fragmentLoginMainText.getTypeface());
materialTextView.setTextSize(fragmentLoginBinding.fragmentLoginMainText.getTextSize());
etc...
fragmentLoginBinding.getRoot().addView(materialTextView);
CodePudding user response:
You don't clone existing views, the system doesn't work that way. However if the view is in xml, you can inflate a new copy. LayoutInflater.from(context).inflate(layoutId, fragmentLoginBinding.getRoot())
will inflate it and add it to that parent. If you don't want to inflate the entire xml file, then you probably need to break it out into its own xml file and include one into the other with the <include>
tag