【问题标题】:ChildActivity extends BaseActivity, how to bind views in layout set with LayoutInflater::inflate?ChildActivity 扩展 BaseActivity,如何使用 LayoutInflater::inflate 绑定布局集中的视图?
【发布时间】:2018-02-11 01:29:23
【问题描述】:

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

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 时,我又回到了原点。我该如何解决?

【问题讨论】:

标签: android android-layout butterknife


【解决方案1】:

以及使用 LayoutInflater 的 inflate() 调用设置的布局

getLayoutInflater().inflate返回一个全新的View,它需要与activity内容视图分开绑定。如果你想使用那个视图,你不需要膨胀它,因为你只是用布局ID调用setContentView。

不过,如果您想使用 FrameLayout 执行此操作,我建议您使用 Fragments。

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

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

【讨论】:

  • 这个答案太短了。 View v = getLayoutInflater().inflate(R.layout.child, content); 后跟 Butterknife.bind(this, v) 也是我尝试过的。同样的错误!
  • 因为this是Activity,只有FrameLayout、DrawerLayout和Toolbar
  • 请查看我对 ChildActivity 类所做的编辑。我忘了在 BaseActivity 中添加 @BindView(R.id.content) FrameLayout content;,这是一个 FrameLayout。这有什么改变吗?
  • 否则你是说我正在尝试做的事情目前无法通过活动来实现?否则我没有机会切换回片段。
  • 并非如此。您的 RecyclerView 不在 Activity 内容视图中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-26
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多