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



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)

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

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

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


如果要在布局中添加多个视图,则需要夸大多个视图,并分别添加它们。

for (...) {
  View view = inflate(..) // inflate new view
  layout.addView(view); // add new view
}

错误消息是自式的。

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

相关内容

最新更新