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

时间:2016-10-11 05:45:37

标签: android android-fragments android-viewpager tabbed-view android-tabbed-activity

我的主要活动上有一个标签式视图和一个浮动操作按钮。每当我点击浮动操作按钮时,我想调用我的片段代码中存在的方法。我尝试了很多东西,但是它说的是

  

尝试在空对象引用上调用虚方法'void com.shyamzawar.makeMyResume.fragments.EducationalDetailsFragment.showChangeLangDialog()'

这是我的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();
}

}

3 个答案:

答案 0 :(得分:1)

您的EducationalDetailsFragment对象似乎为null。使用此选项可从viewpager中检索您的片段。这是一个更好的做法:

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

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

答案 1 :(得分:1)

您可以全局声明您的educationFragment

private EducationalDetailsFragment mEducationalDetailsFragment;


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


onYourFabClickListerner(){
     call the method by using mEducationalDetailsFragment
}

答案 2 :(得分:0)

更改片段:

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

}