如何从 android 中的 activity 调用片段方法?

How to call a fragment method from an activity in android?

我有一个选项卡式视图和一个浮动操作按钮 Activity。每当我单击浮动操作按钮时,我都想调用片段代码中存在的方法。我尝试了很多东西,但它说

Attempt to invoke virtual method 'void com.shyamzawar.makeMyResume.fragments.EducationalDetailsFragment.showChangeLangDialog()' on a null object reference

这是我的 UserDetailsActivity 代码:

public class UserDetailsActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ViewPagerAdapter adapter;

private int currentPage;

private FloatingActionButton fab;

private int readFileRequestCode;

private int[] tabIcons = {
        R.drawable.ic_account_circle_white,             //0 Personal Details
        ...
        R.drawable.ic_create_white_36dp,                //7 Declaration
};

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

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

    //Set Title according to the user clicked
    String name = "Shyam Zawar";
    this.setTitle(name+"'s Profile");

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

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    viewPager.addOnPageChangeListener(new DetailOnPageChangeListener());



    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();

    fab.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            if (currentPage>0)
            {
                switch (currentPage)
                {
                    case 1:
                        FragmentManager manager = getSupportFragmentManager();
                        EducationalDetailsFragment educationalDetailsFragment = (EducationalDetailsFragment) manager.findFragmentById(R.id.EduFragment);
                        educationalDetailsFragment.showChangeLangDialog();
                        break;
                }
            }
        }
    });
}


private void setupTabIcons()
{
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    ...
    tabLayout.getTabAt(7).setIcon(tabIcons[7]);
}

private void setupViewPager(ViewPager viewPager)
{
    adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new PersonalDetailsFragment(), " PERSONAL DETAILS");            //0
    ...
    adapter.addFrag(new DeclarationFragment(), " DECLARATION");                     //7
    viewPager.setAdapter(adapter);
}

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

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

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

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

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

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

这是 EducationalDetailsFragment.java

的代码
public class EducationalDetailsFragment extends Fragment{

private FloatingActionButton fab;
private TextView TextViewEduDetails;

public EducationalDetailsFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

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

    View view = inflater.inflate(R.layout.fragment_educational_details, container, false);

    TextViewEduDetails = (TextView) view.findViewById(R.id.TextViewEduDetails);

    return view;
}

public void setData(String stringData)
{
    TextViewEduDetails.setText(stringData);
}

public void showChangeLangDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.educational_details_dialog, null);
    dialogBuilder.setView(dialogView);

    dialogBuilder.setTitle("Educational Details");
    dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {}
    });
    dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {}
    });
    AlertDialog b = dialogBuilder.create();
    b.show();
}

}

您的 EducationalDetailsFragment 对象似乎为空。使用它从您的 viewpager 中检索您的片段。这是一个更好的做法:

Fragment EducationalDetailsFragment = viewPager.getAdapter().getItem(index);

如果你不知道index。您可以在创建片段时为片段设置标签,并通过 viewpager 适配器中的标签找到它们 ;)

更改片段:

public void changeFragment(Fragment fragment){
    fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.content,
            fragment).commit();

}

您可以全局声明您的 educationFragment

private EducationalDetailsFragment mEducationalDetailsFragment;


//in your setupViewPager() method
mEducationalDetailsFragment = new EducationalDetailsFragment();
adapter.addFrag(mEducationalDetailsFragment , "Whatever the Name");


onYourFabClickListerner(){
     call the method by using mEducationalDetailsFragment
}