使用FragmentPagerAdapter从主活动中调用Fragment方法

时间:2018-07-22 06:41:41

标签: java android android-fragments android-viewpager android-fragmentactivity

我想从MainActivity调用My Fragment方法。我从here找到了很好的解决方案。我正在学习android,因此技术知识不多。我几乎没有什么不同。我在MainActivity中使用FragmentPagerAdapter,如下所示:

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

我的ViewPager如下所示:

   private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "HOME");
        adapter.addFragment(new AccountFragment(), "ACCOUNT");
        adapter.addFragment(new SetupFragment(), "SETUP");
        viewPager.setAdapter(adapter);
    }

现在我要从MainActivity调用HomeFragment函数。我该怎么办?

作为示例答案,我可以像下面这样:

ExampleFragment fragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag(“FragTagName”); 
fragment.specific_function_name();

但是我不知道如何在使用FragmentPagerAdapter时为片段设置标签。让我知道是否有人可以帮助我解决问题。

MainActivity代码:

public class HomeActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private ViewPager viewPager;
    private BottomNavigationView bottomNavigationView;
    Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView mDrawerList;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mDrawerLayout = findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerToggle.syncState();
        Activity mActivity = this;

        viewPager = findViewById(R.id.viewpager);
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);


        //
        mDrawerList = findViewById(R.id.left_drawer);
        DrawerItem[] drawerItem = new DrawerItem[4];
        drawerItem[0] = new DrawerItem(R.drawable.compare, "Compare");
        drawerItem[1] = new DrawerItem(R.drawable.on, "Notification");
        drawerItem[2] = new DrawerItem(R.drawable.support, "Support");
        drawerItem[3] = new DrawerItem(R.drawable.news, "News");
        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_drawer, drawerItem);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());


        //


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

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    bottomNavigationView.setSelectedItemId(R.id.menuHome);
                } else if (position == 1) {
                    bottomNavigationView.setSelectedItemId(R.id.menuAccount);
                } else {
                    bottomNavigationView.setSelectedItemId(R.id.menuSetup);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        SharedPreferences pref = mActivity.getSharedPreferences("setting", MODE_PRIVATE);
        int membership = pref.getInt("membership", 1);
        if (membership == 0) {
            if (!HomeActivity.this.isFinishing()) {
                AlertManager.createCallbackAlert(mActivity, "Warning", "Trial expired if premium not purchased your account history will be deleted in 1 days", false, "OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }, "BUY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        viewPager.setCurrentItem(1);
                    }
                });
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "HOME");
        adapter.addFragment(new AccountFragment(), "ACCOUNT");
        adapter.addFragment(new SetupFragment(), "SETUP");
        viewPager.setAdapter(adapter);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menuHome:
                viewPager.setCurrentItem(0);

                break;
            case R.id.menuAccount:
                viewPager.setCurrentItem(1);

                break;
            case R.id.menuSetup:

                viewPager.setCurrentItem(2);
                break;
        }


        return true;
    }



    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);

        }

        @Override
        public int getCount() {
            return mFragmentList.size();

        }

        void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    private boolean bIsBackPressed = false;

    public void onBackPressed() {

        if (!bIsBackPressed) {
            if (this.mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                this.mDrawerLayout.closeDrawer(GravityCompat.START);
            } else {
                Toast.makeText(this, "Press Back again to exit", Toast.LENGTH_SHORT)
                        .show();
                bIsBackPressed = true;
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception pE) {
                            Log.e("BackPressed Error", Log.getStackTraceString(pE));
                        }
                        bIsBackPressed = false;
                    }
                }).start();
            }
        } else
            finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item))
            return true;


        return super.onOptionsItemSelected(item);
    }



    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);

        }

    }

    private void selectItem(int position) {


        switch (position) {
            case 0:
                Toast.makeText(HomeActivity.this,"Clicked",Toast.LENGTH_SHORT).show();
                break;
            case 1:
                changeNotification();
                /*Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(constant.URL_PRIVACY));
                startActivity(i);*/
                break;
            case 2:
                startActivity(new Intent(HomeActivity.this, SupportActivity.class));
                break;
                /*Intent web = new Intent(Intent.ACTION_VIEW);
                web.setData(Uri.parse(constant.URL));
                startActivity(web);*/
            case 3:
                startActivity(new Intent(HomeActivity.this, NewsActivity.class));
                break;

            default:
                break;
        }
            mDrawerLayout.closeDrawer(mDrawerList);


    }

    public void changeNotification() {
        final Dialog dialog = new Dialog(HomeActivity.this);
        //  dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
        dialog.setContentView(R.layout.dialog_change_sound);
        dialog.setCancelable(true);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        RecyclerView rvSounds = dialog.findViewById(R.id.rvSounds);
        rvSounds.setLayoutManager(new LinearLayoutManager(dialog.getContext()));
        rvSounds.setAdapter(new SoundsAdapter(dialog.getContext()));

        dialog.findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
        dialog.getWindow().setAttributes(lp);
    }
}

我要在行中添加方法:

case 0:           
  Toast.makeText(HomeActivity.this,"Clicked",Toast.LENGTH_SHORT).show();
  break;

谢谢。

2 个答案:

答案 0 :(得分:1)

在活动顶部添加ViewPagerAdapter pagerAdapter;

然后使用它来创建ViewPager适配器

pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

然后使用它来访问ViewPager的首页

Fragment fragment = pagerAdapter.getItem(0);

首先确保上面的语句返回的不是null,并且该片段为HomeFragment。现在将片段转换为HomeFragment并调用方法

((HomeFragment) fragment).yourMethod();

答案 1 :(得分:0)

如果您在主要活动中具有ViewPagerAdapter的可访问实例,则可以使用它来访问片段。如果您需要访问第一个frament,请执行以下操作:

Fragment fragment = adapter.getItem(0);

如果必须访问HomeFragment中定义的特定方法,则可以执行以下操作:

((HomeFragment) fragment).yourMethod();

我还建议您在访问片段的方法之前考虑片段的生命周期。