从选项卡式活动中的片段更改FloatingActionButton

时间:2018-10-20 20:04:54

标签: android android-fragments floating-action-button

你好吗? 我是android编程的新手。我面临一个我试图解决的问题。但是,我做不到。 我创建了一个新项目。选项卡式活动。

我更改了其中的一些设置。 对于每个选项卡,我创建一个片段。 我将默认的floatActionButton保留在MainActity布局中。 我试图从一个片段访问它。

出现错误。 这是我的MainActivity类:

C:\WINDOWS\system32>where node
C:\Program Files\nodejs\node.exe

我的摘要片段如下:

public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.Main_FAB);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


}

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position)
        {
            case 0 : Summary summary = new Summary(); return summary ;
            case 1 : Expense_items expenseItems = new Expense_items(); return expenseItems;
            case 2 : Linage_items linage_items= new Linage_items(); return linage_items;
            default: return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}
}

在MainActivity布局中,我创建了floatActionButton,如下所示:

public class Summary extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_summary, container, false);
    TextView summary_text = (TextView) rootView.findViewById(R.id.summary_text);
    summary_text.setText("You are in Summary Fragment Fragment");
    FloatingActionButton myFB  = (FloatingActionButton) rootView.findViewById(R.id.fab);

    return rootView;
}
}

我不想在片段中创建FloatingActionButton的原因是因为我不想更改其在布局中的位置。

3 个答案:

答案 0 :(得分:1)

您必须处理正在处理所有片段的MainActiviy中的浮动按钮。 尝试在您的MainActity中执行此操作:

         myFab = (FloatingActionButton) findViewById(R.id.Main_FAB);
    myFab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), iconIntArray[0]));

    myFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int position = tabLayout.getSelectedTabPosition();

            switch (position) {
                case 0:
                    myFab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, iconIntArray[0]));

                    intent = new Intent(MainActivity.this,
                            EnterExpensesActivity.class);
                    intent.putExtra("USER_ID",USER_ID);
                    intent.putExtra("FRAGMENT",0);

                    intent.putExtra("TITLE",getResources().getString(R.string.Enter_Expense_title));
                    intent.putExtra("FILED",getResources().getString(R.string.Enter_Expense_text));
                    startActivity(intent);

                    break;
                case 1:
                    myFab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, iconIntArray[position]));
                    intent = new Intent(MainActivity.this,
                            Enter_E_L_Items.class);
                    intent.putExtra("USER_ID",USER_ID);
                    intent.putExtra("FRAGMENT",0);

                    intent.putExtra("TITLE",getResources().getString(R.string.Enter_Expense_title));
                    intent.putExtra("FILED",getResources().getString(R.string.Enter_Expense_text));

                    startActivity(intent);
                    /*
                    Snackbar.make(view, "Expenses ", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();*/
                break;
                case 2:
                    myFab.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, iconIntArray[position]));
                    intent = new Intent(MainActivity.this,
                            Enter_E_L_Items.class);
                    intent.putExtra("USER_ID",USER_ID);
                    intent.putExtra("FRAGMENT",1);
                    intent.putExtra("TITLE",getResources().getString(R.string.Enter_Liange_title));
                    intent.putExtra("FILED",getResources().getString(R.string.Enter_Linage_text));

                    startActivity(intent);
                    /*
                    Snackbar.make(view, "Linage ", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();*/
                    break;
            }
        }
    });

我假设您使用的是默认的“标签活动”

您可以将浮动按钮的动画设置为:

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewpager.setCurrentItem(tab.getPosition());
            animateFab(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
    setupTabIcons();

}

我创建了animateFab方法,如下所示:

    protected void animateFab(final int position) {
    final FloatingActionButton fab = findViewById(R.id.Main_FAB);
    fab.clearAnimation();

    // Scale down animation
    ScaleAnimation shrink = new ScaleAnimation(1f, 0.1f, 1f, 0.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    shrink.setDuration(100);     // animation duration in milliseconds
    shrink.setInterpolator(new AccelerateInterpolator());
    shrink.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            // Change FAB color and icon
            fab.setBackgroundTintList(ContextCompat.getColorStateList(getApplicationContext(), colorIntArray[position]));
            fab.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), iconIntArray[position]));

            // Rotate Animation
            Animation rotate = new RotateAnimation(60.0f, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                    0.5f);
            rotate.setDuration(150);
            rotate.setInterpolator(new DecelerateInterpolator());

            // Scale up animation
            ScaleAnimation expand = new ScaleAnimation(0.1f, 1f, 0.1f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            expand.setDuration(150);     // animation duration in milliseconds
            expand.setInterpolator(new DecelerateInterpolator());

            // Add both animations to animation state
            AnimationSet s = new AnimationSet(false); //false means don't share interpolators
            s.addAnimation(rotate);
            s.addAnimation(expand);
            fab.startAnimation(s);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    fab.startAnimation(shrink);
}

答案 1 :(得分:0)

从片段中,您可以通过

访问MainActivity
(MainActivity) getActivity()

在MainActivity中,您可以创建

之类的函数。
public void actionA()

并通过

从片段A调用它
((MainActivity) getActivity()).actionA()

fragmentB等中的actionB。

答案 2 :(得分:0)

首先,我看到在您的MainActivity的XML文件中,晶圆厂的ID为“ Main_FAB” 不是您在此处写的“ fab”

    FloatingActionButton myFB  = (FloatingActionButton) rootView.findViewById(R.id.fab);

另外,您的晶圆厂处于活动状态,而不是零散的,因此要访问它,您需要在自己的工厂中覆盖 片段类 onActivityCreated 方法,在这里您可以获取FloatingActionButton的一个实例。

这是一个应该为您工作的示例。

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myFab = (FloatingActionButton) getActivity().findViewById(R.id.Main_FAB);
}