(Android)如何从fragmentActivity中调用片段中的方法

时间:2013-12-02 07:24:49

标签: android android-fragments android-fragmentactivity

我的布局如下:

enter image description here

我的fragmentActivity使用ViewPager + TabHost

标签标签中有3个标签

“save”按钮位于我的fragmentActivity

我希望在单击“保存”按钮

时通过调用save()方法保存所有3个选项卡中的数据

但我不知道怎么称呼他们

有没有办法从子片段调用方法?

这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actreg);     
    this.initialiseTabHost(savedInstanceState);



    intialiseViewPager();
    save=(Button)findViewById(R.id.save);
   save.setOnClickListener(new OnClickListener() {
    .....
        }

    }
});
}

private void initialiseTabHost(Bundle args) {



     tabHost = (TabHost)findViewById(android.R.id.tabhost);
     tabHost.setup();
    TabInfo tabInfo = null;
     FragmentActivity.AddTab(this, this.tabHost, this.tabHost.newTabSpec("Tab1").setIndicator("Tab1"),
            (tabInfo = new TabInfo("Tab1", fragment1.class, args)));
    this.myHashMapTabInfo.put(tabInfo.tag, tabInfo);
    ......



    tabHost.setOnTabChangedListener(new OnTabChangeListener() {.....
        }
    });
}
@Override

private static void AddTab(fragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}
private class TabInfo {
    private String tag;
    private Class<?> clss;
    private Bundle args;
    private Fragment fragment;

    TabInfo(String tag, Class<?> clazz, Bundle args) {
        this.tag = tag;
        this.clss = clazz;
        this.args = args;
    }
}
class TabFactory implements TabContentFactory {

    private final Context mContext;

    public TabFactory(Context context) {
        mContext = context;
    }

    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }
}

4 个答案:

答案 0 :(得分:0)

只需将数据放入全局变量中,在Activity中定义它。

答案 1 :(得分:0)

未来的Google员工 - Call an activity method from a fragment

从片段到活动:

((YourActivityClassName)getActivity()).yourPublicMethod();

从活动到片段:

FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:

YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");

答案 2 :(得分:0)

创建一个包含按钮的setOnClickListener的公共方法。 这个方法,你可以从Fragment调用这种方式:

((YourActivityClassName)getActivity()).yourPublicMethod();

答案 3 :(得分:-1)

您已保存myHashMapTabInfo中的所有数据。所以你只需要写一个方法来保存myHashMapTabInfo按钮中的save

save.setOnClickListener(new OnClickListener() {
    saveInfo(myHashMapTabInfo);
};