ButterKnifeがアップデートされたよって話
Androiderみんな大好きJakeWharton神のプラグイン,ButterKnifeがv7.0にアップデート(現時点ではv7.0.1)されたら割と色々変わったらしい.
Changelogを見てみる
すごい要約するとこんな感じ
@InjectView
と@InjectViews
の代わりに@Bind
を使うことになったよ!ButterKnife.inject
とButterKnife.reset
がそれぞれButterKnife.bind
,ButterKnife.unbind
に変わったよ!@Optional
アノテーションがなくなってsupport-annotationsとかにある@Nullable
を使うようになったよ!@Bindxxx
でResource Bindingができるようになったよ!
ちなみに@Optional
は「そのレイアウト上に存在しないかもしれない」Viewを定義するときのアノテーション.
んで,何が変わったのさ
上2点は,そのまま置換しましょうねーって内容.新しく書くときは複数のViewをinject/bindするときに複数形にしなくても@Bind
でOKになったよって変更くらい…かな?
FragmentのonDestroyView
でのButterKnife.reset -> ButterKnife.unbind
に関しては下の記事にも書いてあるように記述することをよく忘れがちなので忘れないようにしよう.じゃないと正しくViewが破棄されずにつらいことに
@Optional
アノテーションの廃棄からの@Nullable
の件に関してはsupport-annotationsの@Nullable
でも他のライブラリ等で使われている同名のアノテーションでも大丈夫らしい.
んで,Resource Binding.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" > <TextView android:id="@+id/text_hoge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_centerHorizontal="true"/> </RelativeLayout>
こんなかんじにViewを定義して
<string name="hello_world">Hello world!</string>
XMLにリソース書いて
public class MainFragment extends Fragment { private static final String TAG = MainFragment.class.getSimpleName(); private final MainFragment self = this; @Bind(R.id.text_hoge) TextView mHogeText; @BindString(R.string.hello_world) //String Resource Binding String mHelloWorld; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.bind(this,rootView); mHogeText.setText(mHelloWorld); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } }
Fragmentを書いてあげると
こんな感じに,getString(R.string.hoge)
とかしてあげなくても,ちゃんとStringにXMLで指定したリソースがbindされる.便利っぽい.当たり前っちゃ当たり前だけど@BindString
はString
に,@BindBool
はBoolean
にと,ちゃんと型を合わせないとビルド時に落ちるので注意.(書いてる人は@BindString
をTextView
に当てたらそのままsetText
されるのかと勘違いして見事に死にました)
まとめ
ライブラリとかの最新の動きはちゃんと追いかけないとダメだなーって思いました.急ぎで雑な記事ですいませんでした(土下座)