【发布时间】:2019-09-02 10:13:18
【问题描述】:
我正在尝试更改我的ConstraintLayout 我的代码的背景:
fragment_user.xml
<fragment
android:id="@+id/profile"
android:name="com.app.ProfileFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity"
xmlns:tools="http://schemas.android.com/tools"/>
fragment_profile.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/colorPopupBackground"
android:fadeScrollbars="false"
android:id="@+id/profile_layout">
UserFragment.kt
private fun showProfile(){
val fragment = childFragmentManager.findFragmentById(R.id.profile)!!
fragment.view!!.findViewById<ConstraintLayout>(R.id.profile_layout).setBackgroundColor(ContextCompat.getColor(activity!!, R.color.colorPrimaryDark))
profile_layout.setBackgroundColor(ContextCompat.getColor(activity!!, R.color.colorPrimaryDark))
}
我实际上在profile_layout 上得到了一个NullPointException。知道为什么吗?
错误日志:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.constraintlayout.widget.ConstraintLayout.setBackgroundColor(int)' on a null object reference
at com.app.UserFragment.showProfile(UserFragment.kt:114)
at com.app.UserFragment.onClick(UserFragment.kt:87)
at android.view.View.performClick(View.java:7251)
at android.view.View.performClickInternal(View.java:7228)
at android.view.View.access$3500(View.java:802)
at android.view.View$PerformClick.run(View.java:27843)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7116)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
【问题讨论】:
-
您是否从布局中分配了它?
profile_layout = findViewById(R.id.profile_layout) -
你能发布你的错误日志吗
-
添加了 logcat @sasikumar
-
是的,我得到了同样的空异常@MetaSnarf 我在我的编辑中添加了代码
-
从哪里调用 showProfile。 onViewCreated()?你在使用 kotlin 合成器吗?将 showProfile 移至 onViewCreated。