如何在ViewPager中从单个片段更新Fragment to Activity的值?

时间:2016-01-21 12:43:46

标签: java android android-activity android-viewpager fragmentpageradapter

我正在编写PagerAdapter

的以下代码
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            fragment_edit_delivery_location = new Fragment_edit_delivery_location_Map();
            Bundle arg = new Bundle();
            arg.putString("delivery_to_title_map", "Map Location");
            fragment_edit_delivery_location.setArguments(arg);
            return fragment_edit_delivery_location;


        case 1:
            fragment_edit_delivery_locationHome = new Fragment_edit_delivery_locationHome();
            Bundle arg1 = new Bundle();
            arg1.putString("delivery_to_title_home", "Home");
            fragment_edit_delivery_location.setArguments(arg1);
            return fragment_edit_delivery_location;
}
}

我收到错误错误 的 java.lang.IllegalStateException: Can't change tag of fragment Fragment_edit_delivery_location_Map

适配器的构造函数

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

我在MainActivity中使用ViewPager

adapter = new ActionTabAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);

我正在尝试从当前的片段获取动态值,并再次在MainActivity中用于将String值作为意图发送从 MainActivity SecondActivity 。 ....但也无法从Current Frgment获得准确的价值.....感谢任何形式的帮助

1 个答案:

答案 0 :(得分:0)

使用回叫可以帮助你

1)创建一个界面

Any

}

2)在你的片段类中这样做 TextCallback textCallback;

textCallback.getcalltochangeText(" BREW TEA");

public interface TextCallback {
void getcalltochangeText(String txt);
void getArrayToset(ArrayList<String> data);

3)然后在你的主要活动中实现这个界面

   @Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    if(activity instanceof FragmentCommunicator)
    {


        fc=(FragmentCommunicator)activity;

    }
    else
    {
        throw  new  ClassCastException();
    }

    if(activity instanceof TextCallback)
    {
        textCallback=(TextCallback)activity;
    }
    else
    {
        throw  new  ClassCastException();

    }
}

//并在此处获取您想要的值