我在尝试用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时,我又回到了原点。我该怎么解决这个问题?
发布于 2018-02-10 17:08:08
和布局设置与一个LayoutInflater的通货膨胀()调用
getLayoutInflater().inflate返回一个全新的视图,它需要与活动内容视图分开绑定。如果您想使用这个视图,您不需要膨胀它,因为您只需要使用布局id调用setContentView。
不过,我建议您在使用FrameLayout时使用片段。
您将使用@BindView FrameLayout,然后使用getSupportFragmentManager()动态添加片段。是否在片段中使用蝴蝶刀是一个实现细节。
至少,在XML中使用<include>标记而不是FrameLayout。存在错误是因为“回收视图”不在绑定实例的上下文中。
https://stackoverflow.com/questions/48723251
复制相似问题