片段中的浮动操作按钮

时间:2018-06-22 15:57:23

标签: java android

我试图在片段中添加一个浮动操作按钮,但是使用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);

“无法访问的声明”

2 个答案:

答案 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)

上面有一个返回值,这意味着无法到达此行代码(及以下代码)。