膨胀类片段android kotlin

时间:2017-06-14 10:25:18

标签: android android-layout android-fragments kotlin inflate-exception

所以,首先我回答你的问题“你真的吗?有很多答案。”是的,我知道,但我真的试图解决这个问题,就像第三天一样:在所有SOF中,对我的错误毫无疑问。我有两个类似的项目:Java和Kotlin。但是这个f @#^%!@ ing只在Kotlin中出错。但XML是100%的身份。

所以,错误是:android.view.InflateException: Binary XML file line #8: Error inflating class fragment

我的 activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutMain"
    android:orientation="vertical">

    <fragment
        android:id="@+id/top_fragment"
        android:name="com.example.weatherapp_kotlin.fragments.TopFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </fragment>

    <fragment
        android:id="@+id/bottom_fragment"
        android:name = "com.example.weatherapp_kotlin.fragments.BottomFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="4">
    </fragment>
</LinearLayout>

我试图做的事情:

  • 将XML中的android:name =""更改为class = ""
  • 在第一个位置设置android:nameclass
  • 要将LinearLayout更改为RelativeLayoutConstraintLayout
  • 将班级extends更改为FragmentActivity(现在为Fragment并且在 Java工作得很好)
  • 清理项目

我的LinearLayout有一个id,一个orientationandroid:name中的类的路径是正确的。

我尝试使用此类的片段:

class StartActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}}

也许这是一个硬编码,但在Java中它运行良好。 我认为我不需要显示TopFragment.ktBottomFragment.kt因为我试图告诉你我在SOF主题中找到的所有内容。但如果你需要 - 我会表明。但是,XML文件中存在错误,因此可能是XML。

完整的堆栈跟踪:

06-14 15:24:10.161 25861-25861/com.example.weatherapp_kotlin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.weatherapp_kotlin, PID: 25861
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.weatherapp_kotlin/com.example.weatherapp_kotlin.StartActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2472)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:174)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                               at android.os.Looper.loop(Looper.java:194)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5550)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
                                                                            Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
                                                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                                               at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:418)
                                                                               at android.app.Activity.setContentView(Activity.java:2172)
                                                                               at com.example.weatherapp_kotlin.StartActivity.onCreate(StartActivity.kt:9)
                                                                               at android.app.Activity.performCreate(Activity.java:6003)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2425)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534) 
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:174) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                                               at android.os.Looper.loop(Looper.java:194) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5550) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750) 
                                                                            Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
                                                                               at com.example.weatherapp_kotlin.fragments.TopFragment.onCreateView(TopFragment.kt:0)
                                                                               at android.app.Fragment.performCreateView(Fragment.java:2069)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:875)
                                                                               at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1050)
                                                                               at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1152)
                                                                               at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2142)
                                                                               at android.app.Activity.onCreateView(Activity.java:5347)
                                                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
                                                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
                                                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
                                                                               at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:418) 
                                                                               at android.app.Activity.setContentView(Activity.java:2172) 
                                                                               at com.example.weatherapp_kotlin.StartActivity.onCreate(StartActivity.kt:9) 
                                                                               at android.app.Activity.performCreate(Activity.java:6003) 
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129) 
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2425) 
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534) 
                                                                               at android.app.ActivityThread.access$800(ActivityThread.java:174) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1424) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                                               at android.os.Looper.loop(Looper.java:194) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5550) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:955) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)  

TopFragment.class:

class TopFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {

private var outputCity: String = getString(R.string.output_city)
private var outputClouds: String = getString(R.string.output_clouds)
private var outputHumidity: String = getString(R.string.output_humidity)
private var outputPressure: String = getString(R.string.output_pressure)
private var outputWindspeed: String = getString(R.string.output_windspeed)
private var outputMmhg: String = getString(R.string.output_mmHg)
private var outputMs: String = getString(R.string.output_ms)

private var date: Date = Date()
private var dateFormat: SimpleDateFormat = SimpleDateFormat("E, dd.MM")

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle): View? {
    return inflater.inflate(R.layout.fragment_top, container, false)
}

override fun onStart() {
    super.onStart()

    swipeToRefresh.setOnRefreshListener(this)
    swipeToRefresh.setColorSchemeColors(Color.GREEN, Color.RED, Color.BLUE, Color.CYAN)

    checkInternetConnection(activity)
}

override fun onRefresh() {
    Handler().postDelayed({
        getData(activity)
        swipeToRefresh.setRefreshing(false)
    }, 2500)
}

fun checkInternetConnection(c: Context) {
    if (InternetConnection().isNetworkAvailable(activity)) {
        getData(activity)
    } else {
        Toast.makeText(activity, "Internet Connection Error", Toast.LENGTH_LONG).show()
    }
}

fun getData(c: Context) {
    val apiServiceWeather = RetrofitClient().getApiServiceWeather()
    val call: Call<WeatherModel> = apiServiceWeather.getMyJSON();
    call.enqueue(object: Callback<WeatherModel> {

        override fun onResponse(call: Call<WeatherModel>?, response: Response<WeatherModel>?) {
            val humidity: Int? = response!!.body().getMainWeather().humidity
            val pressure: Float? = response.body().getMainWeather().pressure
            val temperature: Float? = response.body().getMainWeather().temp
            val windspeed: Float? = response.body().getWind().windspeed
            val clouds: Int? = response.body().getClouds().clouds

            textViewDate.setText((dateFormat!!.format(date).toString()))
            textViewCity.setText(outputCity)
            textViewTemp.setText(((Math.rint(temperature!! - 273.15) * 10.0) / 10.0).toString()
                    + "°C")
            textViewCondition.setText(response.body().getWeather().get(0).description)
            textViewClouds.setText(outputClouds + " " + clouds.toString() + "%")
            textViewPressure.setText(outputPressure + " " + (Math.round(pressure!! / 1.3332239))
                    .toString() + " " + outputMmhg)
            textViewHumidity.setText(outputHumidity + " " + humidity.toString() + "%")
            textViewWindspeed.setText(outputWindspeed + " " + windspeed.toString() + outputMs)
        }

        override fun onFailure(call: Call<WeatherModel>?, t: Throwable?) {
            Toast.makeText(activity, "onResponse Error", Toast.LENGTH_LONG).show()
        }
    })
}

}

1 个答案:

答案 0 :(得分:1)

  

引起:java.lang.IllegalStateException:片段TopFragment {37d52abb}未附加到活动
  ...
  在com.example.weatherapp_kotlin.fragments.TopFragment。(TopFragment.kt:24)

我希望这将是私有变量的第一行,您可以调用getString()从资源中获取字符串。

这些字段在对象构造期间初始化,但此时片段未附加到任何上下文。 getString()需要一个来自Context的Resources对象 如果您只是自己创建一个实例(即调用它的构造函数),也会发生这种崩溃。

它包装膨胀异常的原因是因为这些片段是在解析xml布局时创建的。它找到了创建和包含片段的指令,它会这样做但却失败了。

可能的解决方案

1)在lazy委托中包含对getString的调用。这会延迟     首次访问属性时的调用,所以你必须这样做     确保只有在确定时才能访问这些属性     片段附加。例如,在onCreateView()中。

private var outputCity by lazy { getString(R.string.output_city) }

2)用lateinit标记变量,并在第一次时初始化     附在上下文中。现在你必须确保你永远不会访问     之前的属性,或者你受到了欢迎     PropertyNotInitialisedException

private lateinit var outputCity: String

override fun onAttach(context: Activity) {
    super.onAttach(context)
    outputCity = getString(R.string.output_city)
    ...
}
相关问题