指定的孩子已经有一位家长。你必须首先调用孩子父母的removeView()第一个“

问题描述:

我想添加一个20如果Android版本是Kitkat或以上使用Java的marginTop。我收到一个错误指定的孩子已经有一个父母。您必须先调用子对象的父对象的removeView()。 我已经尝试过这些,但无济于事。指定的孩子已经有一位家长。你必须首先调用孩子父母的removeView()第一个“

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

Conflicting Android error messages: The specified child already has a parent. You must call removeView() on the child's parent first

MainActivity.java

package com.appex.tryproject; 

import android.app.ActionBar; 
import android.content.Intent; 
import android.content.IntentSender; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Gravity; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.facebook.CallbackManager; 
import com.facebook.FacebookCallback; 
import com.facebook.FacebookException; 
import com.facebook.FacebookSdk; 
import com.facebook.appevents.AppEventsLogger; 
import com.facebook.login.LoginResult; 
import com.facebook.login.widget.LoginButton; 
import com.gc.materialdesign.views.LayoutRipple; 
import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.SignInButton; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.plus.Plus; 
import com.readystatesoftware.systembartint.SystemBarTintManager; 

public class MainActivity extends ActionBarActivity implements View.OnClickListener, 
     GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 
    private CallbackManager callbackManager; 
    LoginButton loginButton; 
    private static final int RC_SIGN_IN = 0; 
    private GoogleApiClient mGoogleApiClient; 
    private boolean mSignInClicked; 
    ProgressBarCircularIndeterminate p; 
    /** 
    * A flag indicating that a PendingIntent is in progress and prevents us 
    * from starting further intents. 
    */ 
    private boolean mIntentInProgress; 

private ConnectionResult mConnectionResult; 

private SignInButton btnSignIn; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    FacebookSdk.sdkInitialize(getApplicationContext()); 
    setContentView(R.layout.toolbar_main); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_r); 
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT) { 
     LinearLayout Main_layout=(LinearLayout)findViewById(R.id.main_layout); 
     LinearLayout linearLayout=new LinearLayout(this); 
     LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); 
     layoutParams.setMargins(0, 25, 0, 0); 
     linearLayout.removeAllViews(); 
     linearLayout.addView(Main_layout, layoutParams); 
     SystemBarTintManager tintManager = new SystemBarTintManager(this); 
     tintManager.setStatusBarTintEnabled(true); 
     tintManager.setStatusBarTintColor(getResources().getColor(R.color.primary_dark)); 
    } 
    toolbar.setTitleTextColor(getResources().getColor(R.color.primary_text)); 
    setSupportActionBar(toolbar); 
    callbackManager = CallbackManager.Factory.create(); 
    loginButton = (LoginButton)findViewById(R.id.login_button); 
    loginButton.setReadPermissions("user_friends"); 
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 
     @Override 
     public void onSuccess(LoginResult loginResult) { 
      Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show(); 
      Intent intent = new Intent(getApplicationContext(), EventActivity.class); 
      startActivity(intent); 
     } 

     @Override 
     public void onCancel() { 
      Toast.makeText(getApplicationContext(), "Login canceled", Toast.LENGTH_SHORT).show(); 
      Intent intent = new Intent(getApplicationContext(), EventActivity.class); 
      startActivity(intent); 
     } 

     @Override 
     public void onError(FacebookException exception) { 
      Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    TextView orText=(TextView)findViewById(R.id.optionView); 
    orText.setGravity(Gravity.CENTER); 
    LayoutRipple RegisterButton=(LayoutRipple)findViewById(R.id.register); 
    RegisterButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent=new Intent(getApplicationContext(),RegisterActivity.class); 
      startActivity(intent); 
     } 
    }); 
    com.rey.material.widget.Button LoginEmail=(com.rey.material.widget.Button)findViewById(R.id.emailLogin); 
    LoginEmail.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent=new Intent(getApplicationContext(),EmailActivity.class); 
      startActivity(intent); 
     } 
    }); 
    btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in); 

    // Button click listeners 
    btnSignIn.setOnClickListener(this); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this).addApi(Plus.API) 
      .addScope(Plus.SCOPE_PLUS_LOGIN).build(); 
    p = (ProgressBarCircularIndeterminate)findViewById(R.id.progressBarCircularIndeterminate); 
    p.setBackgroundColor(getResources().getColor(R.color.accent)); 
} 

protected void onStart() { 
    super.onStart(); 
    mGoogleApiClient.connect(); 
} 

protected void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.disconnect(); 
    } 
} 
private void resolveSignInError() { 
    if (mConnectionResult.hasResolution()) { 
     try { 
      mIntentInProgress = true; 
      mConnectionResult.startResolutionForResult(this, RC_SIGN_IN); 
     } catch (IntentSender.SendIntentException e) { 
      mIntentInProgress = false; 
      mGoogleApiClient.connect(); 
      p.setVisibility(View.VISIBLE); 
     } 
    } 
} 
@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == RC_SIGN_IN) { 
     if (resultCode != RESULT_OK) { 
      mSignInClicked = false; 
     } 

     mIntentInProgress = false; 

     if (!mGoogleApiClient.isConnecting()) { 
      mGoogleApiClient.connect(); 
      p.setVisibility(View.VISIBLE); 
     } 
    } 
    callbackManager.onActivityResult(requestCode, resultCode, data); 
} 

@Override 
public void onConnected(Bundle bundle) { 
    p.setVisibility(View.GONE); 
    mSignInClicked = false; 
    Intent intent = new Intent(MainActivity.this,EventActivity.class); 
    intent.putExtra("name",Plus.PeopleApi.getCurrentPerson(mGoogleApiClient).getDisplayName()); 
    intent.putExtra("mode","google"); 
    startActivity(intent); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    mGoogleApiClient.connect(); 
} 

@Override 
public void onClick(View v) { 
    switch (v.getId()) { 
     case R.id.btn_sign_in: 
      // Signin button clicked 
      signInWithGplus(); 
      break; 
    } 
} 

@Override 
public void onConnectionFailed(ConnectionResult result) { 
    if (!result.hasResolution()) { 
     GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 
       0).show(); 
     return; 
    } 

    if (!mIntentInProgress) { 
     // Store the ConnectionResult for later usage 
     mConnectionResult = result; 

     if (mSignInClicked) { 
      // The user has already clicked 'sign-in' so we attempt to 
      // resolve all 
      // errors until the user is signed in, or they cancel. 
      resolveSignInError(); 
     } 
    } 
} 
private void signInWithGplus() { 
    if (!mGoogleApiClient.isConnecting()) { 
     mSignInClicked = true; 
     resolveSignInError(); 
    } 
} 
@Override 
protected void onResume() { 
    super.onResume(); 
    if(mGoogleApiClient.isConnected()) { 
     Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); 
     mGoogleApiClient.disconnect(); 
     mGoogleApiClient.connect(); 
    } 
    // Logs 'install' and 'app activate' App Events. 
    AppEventsLogger.activateApp(this); 
} 
@Override 
protected void onPause() { 
    super.onPause(); 
    if(mGoogleApiClient.isConnected()){ 
    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);} 
    // Logs 'app deactivate' App Event. 
    AppEventsLogger.deactivateApp(this); 
} 
} 

main.xml中

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@color/white" 
    android:id="@+id/container"> 
    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:layout_centerVertical="true"> 
     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" 
      android:id="@+id/linearLayout"> 

      <com.facebook.login.widget.LoginButton 
       android:id="@+id/login_button" 
       android:layout_width="200dp" 
       android:layout_height="50dp" 
       android:layout_gravity="center" 
       /> 
      <com.google.android.gms.common.SignInButton 
       android:id="@+id/btn_sign_in" 
       android:layout_width="200dp" 
       android:layout_height="50dp" 
       android:layout_margin="20dp" 
       android:layout_gravity="center" 

       /> 
      <com.gc.materialdesign.views.ProgressBarCircularIndeterminate 
       android:id="@+id/progressBarCircularIndeterminate" 
       android:layout_width="50dp" 
       android:layout_height="50dp" 
       android:background="#1E88E5" 
       android:layout_gravity="center" 
       android:visibility="gone" 
       /> 
      <com.rey.material.widget.Button 
       android:layout_width="200dp" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:drawableLeft="@drawable/ic_email" 
       android:text="@string/emailButton" 
       style="@style/buttong" 
       android:textColor="@color/primary_text" 
       android:id="@+id/emailLogin" 
       android:textAllCaps="false" 
       android:textSize="18.5sp"/> 
     </LinearLayout> 
     <TextView 
      android:layout_width="match_parent" 
      android:layout_marginLeft="10dp" 
      android:layout_marginRight="10dp" 
      android:layout_height="wrap_content" 
      android:text="@string/option" 
      android:textColor="@color/secondary_text" 
      android:textSize="18.5sp" 
      android:gravity="center" 
      android:layout_below="@id/linearLayout" 
      android:layout_marginTop="50dp" 
      android:layout_gravity="center" 
      android:id="@+id/optionView" /> 
     <com.gc.materialdesign.views.LayoutRipple 
      android:id="@+id/register" 
      android:layout_gravity="center" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
      <com.gc.materialdesign.views.ButtonFlat 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:textSize="18.5sp" 
       android:text="@string/reg" 
       android:layout_margin="10dp" 
       android:gravity="center" 
       android:background="@color/primary_dark" 
       /> 
     </com.gc.materialdesign.views.LayoutRipple> 
    </LinearLayout> 
</RelativeLayout> 

toolbar_main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/main_layout"> 

    <android.support.v7.widget.Toolbar 
     android:id="@+id/toolbar_r" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:minHeight="?attr/actionBarSize" 
     app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light" 
     android:background="@color/primary" /> 
    <include 
     layout="@layout/main"/> 
</LinearLayout> 

登录

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.appex.tryproject/com.appex.tryproject.MainActivity}: 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:2237) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286) 
      at android.app.ActivityThread.access$800(ActivityThread.java:144) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:212) 
      at android.app.ActivityThread.main(ActivityThread.java:5135) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:515) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
      at dalvik.system.NativeStart.main(Native Method) 
    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:3562) 
      at android.view.ViewGroup.addView(ViewGroup.java:3415) 
      at android.view.ViewGroup.addView(ViewGroup.java:3391) 
      at com.appex.tryproject.MainActivity.onCreate(MainActivity.java:63) 
      at android.app.Activity.performCreate(Activity.java:5231) 
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286) 
            at android.app.ActivityThread.access$800(ActivityThread.java:144) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:212) 
            at android.app.ActivityThread.main(ActivityThread.java:5135) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:515) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
            at dalvik.system.NativeStart.main(Native Method) 

我得到一个错误指定的孩子已经有一个父。你必须首先对孩子的父母打电话removeView(),在com.appex.tryproject.MainActivity.onCreate(MainActivity.java:63) 这是linearLayout.addView(Main_layout, layoutParams);

你可以这样改变:

linearLayout.removeAllViews(); 

到这样的:

((ViewGroup)Main_layout.getParent()).removeView(Main_Layout); 

的LinearLayout中没有任何意见,但(你刚刚创建的话),所以linearLayout.removeAllViews()调用是多余的。您需要的不是从Main_Layout的新父项中移除所有视图,而是从其父项中移除Main_Layout。

我可能会做,而不是使代码更可读的是包装Main_Layout在另一个布局,这样,那么你可以做这样的事情:

LinearLayout Main_layout=(LinearLayout)findViewById(R.id.main_layout); 
    RelativeLayout wrapper = (RelativeLayout)findViewById(R.id.wrapper); 
    wrapper.removeView(Main_layout); 
    LinearLayout linearLayout=new LinearLayout(this); 
    LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT); 
    layoutParams.setMargins(0, 25, 0, 0); 
    linearLayout.addView(Main_layout, layoutParams); 
    wrapper.addView(linearLayout); 
    //more code 

然后你toolbar_main.xml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/wrapper"> 
    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/main_layout"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar_r" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:minHeight="?attr/actionBarSize" 
      app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
      app:popupTheme="@style/ThemeOverlay.AppCompat.Light" 
      android:background="@color/primary" /> 
     <include layout="@layout/main"/> 
    </LinearLayout> 
</RelativeLayout>