我试图在片段中添加一个浮动操作按钮,但是使用findViewById创建它时出现错误。
public class HomeFragment extends Fragment {
FloatingActionButton fab;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container,false);
fab = (FloatingActionButton) getView().findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), ProfileActivity.class));
}
});
}
}
错误:fab =(FloatingActionButton)getView()。findViewById(R.id.fab);
“无法访问的声明”
答案 0 :(得分:2)
如下更新代码:
public class HomeFragment extends Fragment {
FloatingActionButton fab;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), ProfileActivity.class));
}
});
return view;
}
}
答案 1 :(得分:1)
上面有一个返回值,这意味着无法到达此行代码(及以下代码)。