简体   繁体   English

片段中的浮动操作按钮

[英]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. 我正在尝试向片段添加浮动操作按钮,但是使用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); 错误: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;
        }
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击浮动操作按钮时,片段与另一个片段重叠 - Fragments overlaps another fragment when clicking on floating action button 浮动动作按钮android - Floating Action Button android 浮动操作按钮和CardView - Floating Action Button and CardView 浮动动作按钮锚 - Floating action button anchor 想要使用浮动操作按钮将项目添加到 ViewPager2 中包含的特定片段中的回收视图 - Want to use a floating action button that adds an item to a recyclerview in a specific fragment that is contained in a ViewPager2 有没有办法让浮动操作按钮根据导航主机中当前的片段来执行某些操作? - Is there a way to have a floating action button do something dependant on which fragment is currently in nav host? 当我尝试在片段中显示或隐藏浮动操作按钮时出错 - Error when I Tried to show or hide a Floating Action Button from a fragment 需要在Android片段页面中添加浮动操作按钮错误多个根标签 - Need to add floating action button error Multiple root tags in fragment page in android 浮动动作按钮,没有检查 - Floating Action Button Without Checkable 更改浮动操作按钮背景 - Change Floating Action Button Background
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM