手机和平板电脑的不同布局的牛刀 [英] Butterknife with Different Layouts for Phones and Tablets

查看:94
本文介绍了手机和平板电脑的不同布局的牛刀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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>

该类看起来像这样:

    @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.谢谢!

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!

推荐答案

在视图的@Bind之前添加注释@Nullable,可能为空.

Add annotation @Nullable before @Bind of the view that might be null.

来自黄油刀网站的示例:

@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;

这篇关于手机和平板电脑的不同布局的牛刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆