Вызов метода фрагмента из действия с FragmentPagerAdapter не работает? - PullRequest
0 голосов
/ 06 января 2019

Я пытаюсь создать макет вкладки с разными фрагментами, я хочу вызвать метод My Fragment из DashboardActivity. В DasboardActivity нравится ниже. После использования этого кода приложение не работает. Кто-нибудь может решить мою проблему с кодом? Спасибо за вашу помощь.

DasboardActivity.java

public class DasboardActivity extends AppCompatActivity {
private ViewPager mViewPager;
private TabLayout mTabLayout;

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

    Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar2);
    setSupportActionBar(toolbar2);


    mTabLayout = (TabLayout) findViewById(R.id.tabs);
    mTabLayout.setupWithViewPager(mViewPager);

    //add the tabs
    mTabLayout.addTab(mTabLayout.newTab().setText("Live Score"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Upcoming"));
    mTabLayout.addTab(mTabLayout.newTab().setText("Ranking"));
    mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);

    PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), mTabLayout.getTabCount());

    mViewPager.setAdapter(adapter);

    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            mTabLayout.setScrollPosition(position, 0, true);
            mTabLayout.setSelected(true);

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

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

        }

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

        }
    });

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.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();
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, 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.
    switch (item.getItemId()){
        case R.id.action_settings:

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            String sharebody="Your Body text";
            shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,sharebody);
            startActivity(Intent.createChooser(shareIntent, "Share App.."));

            break;
    }


    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

}


/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class GooglePlusFragmentPageAdapter extends FragmentPagerAdapter {

    public GooglePlusFragmentPageAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return PlaceholderFragment.newInstance(position + 1);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";

        }
        return null;
    }
}
}

И в коде PageAdapter нравится ниже.

PagerAdepter.java

public class PagerAdapter extends FragmentStatePagerAdapter {

int tabCount;

public PagerAdapter(FragmentManager fm, int tabCount){
    super(fm);
    this.tabCount=tabCount;
}

@Override
public Fragment getItem(int position) {
    switch(position){
        case 0 :
            Tab1Fragment tab1Fragment=new Tab1Fragment();
            return tab1Fragment;
        case 1 :
            HomeFragment homeFragment=new HomeFragment();
            return homeFragment;
        case 2 :
            MoreFragment moreFragment=new MoreFragment();
            return moreFragment;
        default: return null;
    }
}

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