我正在使用Nav抽屉的项目。
<android.support.design.widget.NavigationView
...
app:headerLayout="@layout/home_nav_header" />
标题布局包含一个TextView和一个将保存用户名和用户pic的ImageView。 home_nav_header文件如下所示:
<LinearLayout ...>
<ImageView
android:id="@+id/nav_drawer_user_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
app:srcCompat="@mipmap/ic_launcher_round" />
<TextView
android:id="@+id/nav_drawer_user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
</LinearLayout>
在我的HomeActivity中,我以这种方式设置数据:
import kotlinx.android.synthetic.main.home_content.*
import kotlinx.android.synthetic.main.home_nav_header.*
/...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
mPresenter = HomePresenter(this)
//Fill user name
mUser = intent.getParcelableExtra(LoginActivity.INTENT_USER)
val userName: String = mUser.firstName + " " + mUser.lastName
nav_drawer_user_name.text = userName
//Fill user image
val decodedString = Base64.decode(mUser.photoUrl, Base64.DEFAULT)
val decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
val userImageDrawable = BitmapDrawable(getResources(), decodedByte)
nav_drawer_user_name.background = userImageDrawable
}
我检查过userName和userImageDrawable都不是null。
问题是,当我尝试在TextView和ImageView中填充数据时,应用程序崩溃时出现以下错误:
java.lang.IllegalStateException: findViewById(R.id.nav_drawer_user_name)不能为空
我的代码中缺少什么?
答案 0 :(得分:0)
您必须先获取视图,然后才能为其指定值。
import kotlinx.android.synthetic.main.home_content.*
import kotlinx.android.synthetic.main.home_nav_header.*
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
mPresenter = HomePresenter(this)
//Fill user name
mUser = intent.getParcelableExtra(LoginActivity.INTENT_USER)
val userName: String = mUser.firstName + " " + mUser.lastName
val nav_drawer_user_name = findViewById<TextView>(R.id.nav_drawer_user_name)
nav_drawer_user_name.text = userName
//Fill user image
val decodedString = Base64.decode(mUser.photoUrl, Base64.DEFAULT)
val decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
val userImageDrawable = BitmapDrawable(getResources(), decodedByte)
nav_drawer_user_name.background = userImageDrawable
}
请注意val nav_drawer_user_name = findViewById<TextView(R.id.nav_drawer_user_name)
答案 1 :(得分:0)
我认为kotlin android插件存在问题,我在onCreate,onStart和onResume上尝试了同样的错误但是如果我设置文本onClick的东西,它正常工作。如果你仍然想要setText(或该视图的任何其他方法),你可以按传统方式进行
val textView = nav_view.getHeaderView(0).findViewById<TextView>(R.id.nav_drawer_user_name)
textView.text= "new Text"