java 隐藏另一个布局的浮动操作按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34065037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:26:05  来源:igfitidea点击:

Hide a Floating Action Button of another Layout

javaandroidfloating-action-buttonnestedscrollview

提问by Dolan

I have a FloatingActionButtoninside of may activity_main.xmllayout which is named fabBtn.

我有一个FloatingActionButton5月的内部activity_main.xml布局被命名fabBtn

My application is built with a ViewPagerand three Fragments.I want to hide the FloatingActionButtonwhen my first Fragmentdetects a scroll, but I keep getting a NullPointerExceptionif the user starts scrolling.

我的应用程序是用一个ViewPager和三个构建的,当我第一次检测到滚动时,我Fragment想隐藏它,但是如果用户开始滚动,我会一直得到一个。FloatingActionButtonFragmentNullPointerException

I believe it could be that my fragment can't get the FloatingActionButtonfrom the activity_main.xmllayout?

我相信可能是我的片段无法FloatingActionButtonactivity_main.xml布局中获取?

Here is my activity_main.xml

这是我的 activity_main.xml

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lh.com.newme.MainActivity"
xmlns:fab="http://schemas.android.com/tools">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_scrollFlags="scroll|snap"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:tabMode="fixed"
            app:layout_scrollFlags="snap|enterAlways"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="#ffffff" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabBtn"
        android:layout_marginBottom="@dimen/codelab_fab_margin_bottom"
        android:layout_marginRight="@dimen/codelab_fab_margin_right"
        android:layout_width="wrap_content"
        fab:fab_type="normal"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        app:backgroundTint="@color/fab_ripple_color"
        android:src="@drawable/ic_plus"
        app:fabSize="normal"
        />

    </android.support.design.widget.CoordinatorLayout>

Here is my first Fragmentfrom where I want to hide the FloatingActionButton:

这是我第一个Fragment想要隐藏的地方FloatingActionButton

    public class Ernaehrung extends Fragment {

NestedScrollView nsv;
FloatingActionButton fab;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setHasOptionsMenu(true);

    final View rootView = inflater.inflate(R.layout.ernaehrung, container, false);
    Button Fruehstuck = (Button) rootView.findViewById(R.id.fruehstuck);
    Button Mittagessen = (Button) rootView.findViewById(R.id.mittagessen);
    Button Snacks = (Button) rootView.findViewById(R.id.snacks);

    Fruehstuck.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent FruehstuckScreen = new Intent(getActivity(), lh.com.newme.Fruehstuck.class);
            startActivity(FruehstuckScreen);
        }
    });

    Mittagessen.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent MittagScreen = new Intent(getActivity(), lh.com.newme.Mittagessen.class);
            startActivity(MittagScreen);
        }
    });

    Snacks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent SnackScreen = new Intent(getActivity(), lh.com.newme.Snacks.class);
            startActivity(SnackScreen);
        }
    });

    nsv = (NestedScrollView)rootView.findViewById(R.id.Nsv);
    fab = (FloatingActionButton)rootView.findViewById(R.id.fabBtn);
    nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            if (oldScrollY < scrollY){

                fab.hide();
            }

        else
                fab.show();}


    });

    return rootView;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.main_menu_ernaehrung, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    int id = item.getItemId();
    if (id == R.id.benutzer){

    }
    return super.onOptionsItemSelected(item);
}
} 

This is my MainActivity.class:

这是我的MainActivity.class

  public class MainActivity extends AppCompatActivity {


FloatingActionButton fabBtn;
CoordinatorLayout rootLayout;
Toolbar toolbar;
TabLayout tabLayout;

   ...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
    viewPager.setOffscreenPageLimit(2);

    // Give the TabLayout the ViewPager
    final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.setupWithViewPager(viewPager);

    final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);



    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {

            switch (position) {
                case 0:
                    fab.show();
                    ...
                    break;

                case 1:
                    fab.show();
                    ...
                    break;


                case 2:
                    fab.hide();
                    break;

                default:
                    fab.hide();
                    break;
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    initInstances();
}

private void initInstances() {

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    rootLayout = (CoordinatorLayout) findViewById(R.id.rootLayout);
    fabBtn = (FloatingActionButton) findViewById(R.id.fabBtn);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_menu_edit, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.einstellungen) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}               

回答by Damian Kozlak

First of all, change your line

首先,改变你的线路

final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);

to

fabBtn = (FloatingActionButton)findViewById(R.id.fabBtn);



Solution #1 - get view (if you need object)

解决方案#1 - 获取视图(如果您需要对象)

Then, in your MainActivityadd getter for your FloatingActionButton, like

然后,在你的MainActivityadd getter 中FloatingActionButton,比如

public FloatingActionButton getFloatingActionButton {
    return fabBtn;
}

Finally, in your Fragmentcall:

最后,在您的Fragment通话中:

FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();

and

if (floatingActionButton != null) {
    floatingActionButton.hide();
}

or

或者

if (floatingActionButton != null) {
    floatingActionButton.show();
}



Solution #2 - add two methods in MainActivity(if you need only specific methods, like show()/ hide())

解决方案#2 - 添加两个方法MainActivity(如果您只需要特定的方法,例如show()/ hide()

public void showFloatingActionButton() {
     fabBtn.show();
};

public void hideFloatingActionButton() {
     fabBtn.hide();
};

And in your Fragmentcall to hide:

在你的Fragment隐藏电话中:

((MainActivity) getActivity()).hideFloatingActionButton();

or to show:

或显示:

((MainActivity) getActivity()).showFloatingActionButton();



Note

笔记

If you use more than one Activity, you must check if it's proper Activity:

如果您使用多个Activity,则必须检查它是否正确Activity

if (getActivity() instanceof MainActivity) {
    getActivity().yourMethod(); // your method here
}

回答by Prasanna Anbazhagan

In your fragment your rootView layout is not main layout and you cannot expect the rootView will return the fab button. Thats why you are getting null pointer exception

在您的片段中,您的 rootView 布局不是主布局,您不能期望 rootView 会返回 fab 按钮。这就是为什么你得到空指针异常

You better use interface to detect page scrolling and controll it via your activity

您最好使用界面来检测页面滚动并通过您的活动来控制它