Butterknife与手机和平板电脑的不同布局

时间:2015-12-10 16:24:09

标签: android android-layout screen-size butterknife

我在当前项目中使用Butterknife库时遇到了一些问题。我目前正在针对手机和平板电脑优化项目,例如两者的布局文件之间有时会略有差异

布局/ 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_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>

该类看起来像这样:

    @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;
    }

问题是,由于“text2”视图不存在,因此在手机上查看时会抛出缺少视图的异常。有没有办法解决?或者我必须将findViewById用于所有布局都不可用的视图。谢谢!

1 个答案:

答案 0 :(得分:5)

在可能为null的视图的@Bind之前添加注释@Nullable。

来自ButterKnife Website的示例:

@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;
相关问题