Reputation: 325
I am trying to add a floating action button to my fragment however I am getting an error when creating it using 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));
}
});
}
}
Error: fab = (FloatingActionButton) getView().findViewById(R.id.fab);
"Unreachable statement"
Upvotes: 1
Views: 6316
Reputation: 878
Update your code as below:
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;
}
}
Upvotes: 5
Reputation: 3852
You have a return just above, which means this line of code (and the following) cannot be reached.
Upvotes: 1