如何隐藏特定片段活动的“ fab”按钮?

时间:2019-06-07 19:04:51

标签: java android floating-action-button

如何隐藏单击或打开特定片段的“ fab”按钮?

我想从波纹管片段中隐藏

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View newExchange= inflater.inflate(R.layout.new_exchange,container,false);


        recyclerView=newExchange.findViewById(R.id.step1recycleView);
        datalist=new ArrayList<>();
        exchangeAdapter=new NewExchangeAdapter(datalist,getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(exchangeAdapter);
        loadData();

        FloatingActionButton fab =newExchange.findViewById(R.id.fab);
        fab.setVisibility(View.INVISIBLE);//this is generating error on setVisibility

        return newExchange;




    }

在这里我单击设置fab按钮

fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                 //       .setAction("Action", null).show();

                fragment=new NewExchangeFrag();
                getSupportFragmentManager().beginTransaction().replace(R.id.frame,fragment).commit();
                fab.setVisibility(view.INVISIBLE);//This way also generating error on setVisibility

我还尝试使用fab.hide();,这使我的应用程序崩溃了

正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

您收到错误消息是因为您尝试访问fab,但是在更换了片段之后。我不明白为什么要在删除片段后试图隐藏按钮。该按钮不再存在。

尝试

fab.setVisibility(view.INVISIBLE)

之前

fragment=new NewExchangeFrag()

实际上,您甚至不需要隐藏按钮。

答案 1 :(得分:0)

如果要在片段膨胀时隐藏它,则应在NewExchangeFragment的xml文件中为浮动操作按钮设置可见性属性。

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:visibility="gone"
    app:srcCompat="@android:drawable/ic_dialog_email" />

至于单击时隐藏按钮,应在填充新片段之前调用setVisibility方法

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            view.setVisibility(View.INVISIBLE);
            fragment = new NewExchangeFrag();
            getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).commit();
        }
    });