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"
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;
}
}
您在上面有一个返回值,这意味着无法到达此行代码(及以下代码)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.