ChildActivity扩展了BaseActivity,如何使用LayoutInflater :: inflate绑定布局集中的视图?

时间:2018-02-10 16:56:57

标签: android android-layout butterknife

我尝试使用ButterKnife成功注入视图时遇到了困难。我看到的所有示例都假定Activity扩展AppCompatActivity,并且布局设置为setContentView()。我的案例涉及Activity扩展BaseActivity,并且使用LayoutInflater inflate()来电设置布局:

public class BaseActivity extends AppCompatActivity {
    @BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
    @BindView(R.id.toolbar) Toolbar toolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base);
        ButterKnife.bind(this);
    }
}

这是ChildActivity

public class ChildActivity extends BaseActivity {
    @BindView(R.id.content) FrameLayout content; // content is in the base layout
    @BindView(R.id.recycler_view) RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // content (below) is a FrameLayout in the BaseActivity
        getLayoutInflater().inflate(R.layout.child, content);
        ButterKnife.bind(this);
    }
}

当我运行应用程序时,出现错误:

Required view 'recycler_view' with ID 2131230798 for field 'recyclerView' 
was not found. If this view is optional add '@Nullable' (fields) or 
'@Optional' (methods) annotation.

所以我按照建议添加@Nullable

 @BindView(R.id.recycler_view) @Nullable RecyclerView recyclerView;

另一个错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void
 android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v
7.widget.RecyclerView$LayoutManager)' on a null object reference

当我删除@Nullable时,我会回到原点。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

  

并使用LayoutInflater的inflate()调用

设置布局

getLayoutInflater().inflate返回一个全新的视图,它需要与活动内容视图分开绑定。如果您想使用该视图,则不需要对其进行充气,因为您只需使用布局ID调用setContentView。

如果你想用FrameLayout做这个,我建议你使用Fragments。

你会@BindView FrameLayout,然后使用getSupportFragmentManager()动态添加片段 。您是否在Fragments中使用Butterknife是一个实现细节。

至少,在XML中使用<include>标记而不是FrameLayout。您的错误存在,因为Recyclerview不在绑定实例的上下文中