【问题标题】:How to create a clone from specific a view in Android?如何从 Android 中的特定视图创建克隆?
【发布时间】:2021-11-21 06:20:02
【问题描述】:

如何克隆布局中特定视图的属性?

我有这个观点

<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" />

我想创建这个视图的克隆,我就是这样做的

MaterialTextView materialTextView = fragmentLoginBinding.fragmentLoginMainText;
materialTextView.setId(View.NO_ID);
fragmentLoginBinding.getRoot().addView(materialTextView);

但我得到了这个错误

Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

所以我想知道是否有任何方法可以从该视图创建克隆,而无需像这样手动进行

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);

【问题讨论】:

    标签: android view android-view


    【解决方案1】:

    您不会克隆现有视图,系统不会那样工作。但是,如果视图是 xml 格式,您可以扩充一个新副本。 LayoutInflater.from(context).inflate(layoutId, fragmentLoginBinding.getRoot()) 会将其膨胀并将其添加到该父级。如果您不想膨胀整个 xml 文件,那么您可能需要将其拆分为自己的 xml 文件,并使用 &lt;include&gt; 标签将其包含到另一个中

    【讨论】:

    • 我不知道您在该链接中指的是什么。但就像我说的那样,克隆不是系统的一部分。通货膨胀。
    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多