Ric*_*ick 3 android android-layout screen-size butterknife
我在当前项目中使用Butterknife库时遇到了一些问题。我目前正在针对手机和平板电脑优化该项目,例如,两者的布局文件之间有时会略有差异
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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
该类如下所示:
@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;
}
Run Code Online (Sandbox Code Playgroud)
问题在于,这在电话上查看时会由于缺少视图而引发异常,因为“ text2”视图不存在。有没有办法解决?还是我必须使用findViewById作为并非在所有布局上都可用的视图。谢谢!
在可能为空的视图的@Bind之前添加注释@Nullable。
来自ButterKnife网站的示例:
@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;
Run Code Online (Sandbox Code Playgroud)