活动:您必须首先在孩子的父母上调用removeView()

时间:2017-12-20 19:04:35

标签: android

Android Studio 3.1,Java 1.8。 我想以编程方式向GridLayout添加视图。 所以我使用方法 addView()

这是我的活动代码:

public class ProfileActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = getWindow().getDecorView().getRootView();
        View profileCategoryActive = inflater.inflate(R.layout.profile_category_active, (ViewGroup) view, false);
        TextView categoryNameTextView = profileCategoryActive.findViewById(R.id.categoryNameTextView);
        for (int index = 0; index < categoryCount; index++) {
            categoryNameTextView.setText("Hello " + index);
            gridLayout.addView(profileCategoryActive);
        }
    }
}

但我得到运行时错误:

FATAL EXCEPTION: main
Process: com.myproject.android.customer.debug, PID: 4929
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loyalix.android.customer.debug/com.loyalix.android.customer.ui.ProfileActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:4309)

2 个答案:

答案 0 :(得分:1)

您多次添加相同的视图...

/books

一个视图只能有一个父/被添加到另一个视图,因此是例外。

如果要向布局添加多个视图,则需要对多个视图进行充气,并分别添加每个视图。

for (...) {
  // can't add _same_ view multiple times!
  gridLayout.addView(profileCategoryActive);
}

答案 1 :(得分:1)

错误信息是自我解释的。

    if(profileCategoryActive.getParent()!=null)   
 ((ViewGroup)profileCategoryActive.getParent()).removeView(profileCategoryActive); // Remove view
 gridLayout.addView(profileCategoryActive);