从无关类中调用片段中的方法

时间:2013-12-19 03:41:23

标签: java android-fragments fragment android-fragmentactivity fragmentmanager

这里有棘手的问题,但我会尽力清楚。

A类:extends FragmentActivity并且FragmentManager

B类:extends Fragment并拥有片段的用户界面

C类:无关类

    public class A extends FragmentActivity{
        Fragment fragment = new FragmentActivity();
    }

    public class B extends Fragment{
        public void methodToBeCalled(){
             //do something
}
    }

    public class C{
        //call B's methodToBeCalled() from here
        //note it is not static
    }

我想要做的是从C类调用一个位于B类的方法。任何想法我怎么能这样做?

解决方案是从C类运行此代码的一种方法:

B fragment = (B) getFragmentManager().findFragmentById(R.id.b);

这不起作用(它编译,但if语句总是为false):

    if (A.getCurrentFragment() instanceof B) {
        B fragment = (B) A.getCurrentFragment();
        fragment.methodToBeCalled();
    }

3 个答案:

答案 0 :(得分:0)

将FragmentActivity的上下文传递给C类,使用此上下文,您可以获取片段管理器,然后您可以使用片段ID或标记找到该片段。

FragmentManager fm = context.getSupportFragmentManager();
//tag should same as what you gave while adding the fragment
FragmentB fb=(FragmentB)fm.findFragmentByTag("tag"); 
// call public methods of FragmentB
fb.CallFromClassC();

答案 1 :(得分:0)

使用
FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)

FragmentTransaction.replace (int containerViewId, Fragment fragment, String tag)
为片段设置标签

然后按标签检查片段实例:

A.getCurrentFragment().getTag().equals("btag")

答案 2 :(得分:0)

Step 1 : if class using AsyncTask:

Create a constructor into non-fragment class and parse Fragment Manager:

Step 2:

FragmentManager mFragmentManager;

    // create a constructor
    public NetworkMaster(Activity mMasterActivity){

        this.mFragmentManager = mMasterActivity.getFragmentManager();

    }// end constructor NetworkMaster

Step 3:

protected void onPostExecute(String result) {

            try {

                //ID should same as what you gave while adding the fragment
                SummaryFragment oSummaryFragment = (SummaryFragment)mFragmentManager.findFragmentById(R.id.content_frame); 

                // call public methods of SummaryFragment
                oSummaryFragment.responseFromSummaryUser(result);               

            } catch (Exception e) {
                e.printStackTrace();
            }

        }// end onPostExecute

Step 4: Class the non-fragment class from Fragment:

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

NetworkMaster mNetworkMaster = new NetworkMaster(getActivity());
mNetworkMaster.runUserSummaryAsync();

}