升级后出现片段IllegalStateException

时间:2020-10-15 03:24:01

标签: android android-fragments

当前,我在升级到最新的片段sdk androidx.fragment:fragment:1.1.0应用程序崩溃后正在使用androidx.fragment:fragment:1.2.4。相同的代码在1.1.0上工作,但在1.2.4上崩溃 崩溃报告

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4745)
    at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4696)
    at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4647)
    at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:46)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
 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:5235)
    at android.view.ViewGroup.addView(ViewGroup.java:5064)

1 个答案:

答案 0 :(得分:0)

如果您在片段的onCreateView方法中使用以下内容

# Scrolls down until our nav bar is displayed
    for scrollNum in range(10):
        chrome_driver.execute_script("window.scrollTo(0, {0})".format(scrollNum * 100 + 200))
        time.sleep(2)
        if is_displayed(chrome_driver, "//header[contains(@style, 'visibility: hidden')]") == False:
            break

然后用这个替换它

from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver as ChromeWebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as DriverWait
from selenium.webdriver.support import expected_conditions as DriverConditions
from selenium.common.exceptions import WebDriverException
import time


def get_chrome_driver():
    """This sets up our Chrome Driver and returns it as an object"""
    chrome_options = webdriver.ChromeOptions() 
    chrome_options.add_argument("window-size=1500,1000")
        
    # Removes the "This is being controlled by automation" alert / notification
    chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
    path_to_chrome = "F:\Selenium_Drivers\Windows_Chrome85_Driver\chromedriver.exe"
    return webdriver.Chrome(executable_path = path_to_chrome,
                            options = chrome_options)


def wait_displayed(driver : ChromeWebDriver, xpath : str, int = 3):
    try:
        DriverWait(driver, int).until(
            DriverConditions.presence_of_element_located(locator = (By.XPATH, xpath))
        )
    except:
        raise WebDriverException(f'Timeout: Failed to find {xpath}')
    

def is_displayed(driver : ChromeWebDriver, xpath : str, int = 3):
    try:
        webElement = DriverWait(driver, int).until(
            DriverConditions.presence_of_element_located(locator = (By.XPATH, xpath))
        )
        return True if webElement != None else False
    except:
        return False


# Gets our chrome driver and opens our site
chrome_driver = get_chrome_driver()
chrome_driver.get("https://www.blackhempfamily.com/")


# Repeats this 5 times
for repeat in range(5):
    print("Attempt to click our link. Try #{0}".format(repeat + 1))
    
    is_same_position = False
    final_window_position = 0
    
    # Checks to see if our website's elements display
    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]")
    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]//p[text()='Why Black Hemp?']")
    wait_displayed(chrome_driver, "//nav[contains(@id, 'navContainer')]//p[text()='Shop Black Hemp']")

    # Clicks our "Why Black Hemp?" tab
    chrome_driver.find_element(By.XPATH, "//nav[contains(@id, 'navContainer')]//p[text()='Why Black Hemp?']/../../..").click()
    
    # Checks to see if our page is still scrolling
    while is_same_position == False:
        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")
        time.sleep(2)
        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")
        if(windowPosition1 == windowPosition2):
            is_same_position = True
            final_window_position = windowPosition1
    
    # Checks to see if our "Natural Moisture" text displays
    wait_displayed(chrome_driver, "(//h2//span[contains(., 'Natural Moisture')]/../..)[1]")
    
    # Scrolls back to the top of the page
    chrome_driver.execute_script("window.scrollTo(0, {0})".format((0 - final_window_position)))
    is_same_position = False
    
    # Checks to see if our page is still scrolling
    while is_same_position == False:
        windowPosition1 = chrome_driver.execute_script("return document.body.scrollHeight;")
        time.sleep(2)
        windowPosition2 = chrome_driver.execute_script("return document.body.scrollHeight;")
        if(windowPosition1 == windowPosition2):
            is_same_position = True
    
    # Scrolls down until our nav bar is displayed
    for scrollNum in range(10):
        chrome_driver.execute_script("window.scrollTo(0, {0})".format(scrollNum * 100 + 200))
        time.sleep(2)
        if is_displayed(chrome_driver, "//header[contains(@style, 'visibility: hidden')]") == False:
            break


chrome_driver.quit()
chrome_driver.stop_client()
print('Congratulations! You clicked your link multiple times!')