I am having a bit of an issue with using the Butterknife library in my current project. I am currently optimizing the project for both phones and tablets and there are sometimes slight differences between the layout files for the two for example
layout/layout_example.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text1/>
</LinearLayout>
layout-large/layout_example.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text1/>
<TextView
android:id="@+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text2/>
</LinearLayout>
The Class would look something like this:
@Bind(R.id.text1) TextView text1;
@Bind(R.id.text2) TextView text2;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layout_example, container, false)
ButterKnife.bind(this, rootView);
return rootView;
}
The problem is that this throws an exception for a missing view when viewing on the phone since the "text2" view doesn't exist. Is there anyway around this? or do I have to use findViewById for the views that aren't available on all layouts. Thanks!
Add annotation @Nullable before @Bind of the view that might be null.
Example from ButterKnife Website:
@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;
来源:https://stackoverflow.com/questions/34206862/butterknife-with-different-layouts-for-phones-and-tablets