David G
David G

Reputation: 325

Floating Action Button in Fragment

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

Answers (2)

Vamsi
Vamsi

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

f4.
f4.

Reputation: 3852

You have a return just above, which means this line of code (and the following) cannot be reached.

Upvotes: 1

Related Questions