LoginSignup
6
6

More than 5 years have passed since last update.

DataBindingでContextを引数として渡したい時(getResources()でNullになっちゃう対策)

Last updated at Posted at 2017-01-26

getResources()は困る

contextを渡さずにこんなことをやると、android.content.res.Resources$NotFoundExceptionでクラッシュします。

Hoge.java
public String getHoge() {
Resources resources = Resources.getSystem();
String str = resources.getString(R.string.hoge);
・・・
}

クラッシュする理由

Resources.getSystem()はWhy can't I use Resources.getSystem() without a Runtime error?にも記載がある通り、利用できる場所が限られています。

DataBindingでContextを引数として渡す方法

じゃぁContextを引数として渡してあげればいいんです。

layou.xml
<TextView
 ・・・
 android:text="@{hoge.getHoge(context)}"
/>
Hoge.java
public String getHoge(Context context) {
// これは間違い
//Resources resources = Resources.getSystem();

// こうすればOK
Resources resources = context.getResources();
String str = resources.getString(R.string.hoge);
・・・
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6