Butterknife with Different Layouts for Phones and Tablets

冷暖自知 提交于 2019-12-06 07:31:16

问题


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!


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!