2013-01-21 61 views
11

我需要从5 fragments一个Activity之间传递数据,层出不穷的fragments发送数据的一个,当我到达第5'fragment然后我需要存储的所有5个fragments数据,我们如何能做到这一点。任何想法都是伟大的。 enter image description here传递数据片段之间到活动

回答

32

将数据传递给活动,当活动得到的所有数据,然后对其进行处理。 您可以使用接口传递数据。

片段:

public class Fragment2 extends Fragment { 

    public interface onSomeEventListener { 
    public void someEvent(String s); 
    } 

    onSomeEventListener someEventListener; 

    @Override 
    public void onAttach(Activity activity) { 
    super.onAttach(activity); 
     try { 
      someEventListener = (onSomeEventListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() + " must implement onSomeEventListener"); 
     } 
    } 

    final String LOG_TAG = "myLogs"; 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment2, null); 

    Button button = (Button) v.findViewById(R.id.button); 
    button.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
     someEventListener.someEvent("Test text to Fragment1"); 
     } 
    }); 

    return v; 
    } 
} 

活动:

public class MainActivity extends Activity implements onSomeEventListener{ 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Fragment frag2 = new Fragment2(); 
     FragmentTransaction ft = getFragmentManager().beginTransaction(); 
     ft.add(R.id.fragment2, frag2); 
     ft.commit(); 
    } 

    @Override 
    public void someEvent(String s) { 
     Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1); 
     ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s); 
    } 
} 
+0

嘿Kalyanganov阿列克谢你能elobarate我如何使用接口,如果它是赞赏... –

+1

舒尔一个简单的例子来传递数据。谷歌有很好的例子http://developer.android.com/training/basics/fragments/communicating.html –

+0

但如果我只有一个按钮是在最后一个片段,我该怎么做? HTTP://计算器。com/questions/32953477 /传递数据到片段 – Hoo

5

你必须返回信息到你的片段的活动。而你的活动信息发送给它的片段:

// In fragment A 
((ParentActivity)getActivity()).dispatchInformations("test"); 

// In ParentActivity 
public void dispatchInformations(String mesg){ 
    fragmentB.sendMessage(mesg); 
} 

这是一个基本的例子从各个片段

9

以下链接说明了片段之间的通信的设计。

Communicating with Other Fragments

要允许片段最多传达到它的活动,您可以定义片段中的类的接口和活动中实现它。 Fragment在其onAttach()生命周期方法中捕获接口实现,然后可以调用接口方法以便与Activity进行通信。

这里是片段的到活动通信的示例:

public class HeadlinesFragment extends ListFragment { 

OnHeadlineSelectedListener mCallback; 

// Container Activity must implement this interface 
public interface OnHeadlineSelectedListener { 
    public void onArticleSelected(int position); 
} 

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

    // This makes sure that the container activity has implemented 
    // the callback interface. If not, it throws an exception 
    try { 
     mCallback = (OnHeadlineSelectedListener) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnHeadlineSelectedListener"); 
    } 
} 

... 
} 

现在使用的mCallback实例的片段可以通过调用onArticleSelected()方法(或其它方法在接口)传递消息到活动OnHeadlineSelectedListener接口。

例如,当用户单击列表项时,会调用片段中的以下方法。片段使用回调接口将事件传递给父活动。

@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    // Send the event to the host activity 
    mCallback.onArticleSelected(position); 
} 

实现接口

为了从该片段接收事件回调,承载它必须实现在片段类中定义的接口的活性。

例如,以下活动实现了上述示例中的接口。

public static class MainActivity extends Activity 
    implements HeadlinesFragment.OnHeadlineSelectedListener{ 
... 

public void onArticleSelected(int position) { 
    // The user selected the headline of an article from the HeadlinesFragment 
    // Do something here to display that article 
} 
} 

邮件传递到片段

主机活性可以通过捕捉与findFragmentById(分片实例的片段传送消息),则直接调用片段的公共方法。

例如,假设上面显示的活动可能包含另一个片段,用于显示上述回调方法中返回的数据指定的项目。在这种情况下,该活动可以通过在回调方法收到的其他片段中的信息将显示在项目:

public static class MainActivity extends Activity 
    implements HeadlinesFragment.OnHeadlineSelectedListener{ 
... 

public void onArticleSelected(int position) { 
    // The user selected the headline of an article from the HeadlinesFragment 
    // Do something here to display that article 

    ArticleFragment articleFrag = (ArticleFragment) 
      getSupportFragmentManager().findFragmentById(R.id.article_fragment); 

    if (articleFrag != null) { 
     // If article frag is available, we're in two-pane layout... 

     // Call a method in the ArticleFragment to update its content 
     articleFrag.updateArticleView(position); 
    } else { 
     // Otherwise, we're in the one-pane layout and must swap frags... 

     // Create fragment and give it an argument for the selected article 
     ArticleFragment newFragment = new ArticleFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ArticleFragment.ARG_POSITION, position); 
     newFragment.setArguments(args); 

     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 

     // Replace whatever is in the fragment_container view with this fragment, 
     // and add the transaction to the back stack so the user can navigate back 
     transaction.replace(R.id.fragment_container, newFragment); 
     transaction.addToBackStack(null); 

     // Commit the transaction 
     transaction.commit(); 
    } 
    } 
} 
+0

我这样做,当我点击,iPhone的inthat片段我有一些按钮和编辑文本,然后当我提交我即将到主屏幕。当我点击列表项目的其余部分时,我再次执行相同的操作,当我点击所有信息,然后我需要发送iPhone,黑莓,Android,诺基亚数据到不同的活动。我不知道如何做到这一点。(http://stackoverflow.com/questions/14439941/passing-data-between-fragments-to-activity) –

+0

你能更详细地解释你面临的问题吗?你试图达到什么目标? – Shiva

-1

有从一个片段到另一个活动的数据传递一个非常简单的方式,是不是它的集装箱一个。

1)在片段:当您启动活动,说onButtonClick,传递你想传递作为额外你的意图的数据,例如:

 Intent intent = new Intent(getActivity(), MapsActivity.class); 
    intent.putExtra("data", dataString); 
    startActivity(intent); 

2)在接收活动:在onCreate方法,创建一个包来检索传递的信息,因为这样的:

Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
     receivingString = extras.getString("data"); 
    } else { 
     // handle case 
    } 

希望它能帮助:)

0

我尝试了所有的上方,它没有为我工作。这就是我的工作方式。我使用接口作为将数据从片段发送到活动的手段。

FragmentToActivity.java

public interface FragmentToActivity { 
void communicate(String comm); 

} 

FragmentOne

public class FragmentOne extends Fragment { 

private FragmentToActivity mCallback; 


@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    try { 
     mCallback = (FragmentToActivity) context; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(context.toString() 
       + " must implement FragmentToActivity"); 
    } 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.fragment_login, container, 
false); 
sendData("Andrews"); 

return v; 
} 
@Override 
public void onDetach() { 
    mCallback = null; 
    super.onDetach(); 
} 

public void onRefresh() { 
    Toast.makeText(getActivity(), "Fragment : Refresh called.", 
      Toast.LENGTH_SHORT).show(); 
    } 
private void sendData(String comm) 
    { 
    mCallback.communicate(comm); 

    } 

} 


} 

活动一

public class Account extends AppCompatActivity implements 
    FragmentToActivity{ 

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

@Override 
public void communicate(String s) { 


    Log.d("received", s); 
     } 


} 
0

您可以使用Communicator p attern在上面的答案中解释。 此外,您可以使用RxJava2。以获得更好的解耦和效率。

1-创建总线:

public final class RxBus { 

private static final BehaviorSubject<Object> behaviorSubject 
     = BehaviorSubject.create(); 


public static BehaviorSubject<Object> getSubject() { 
    return behaviorSubject; 
} 

}

2-发件人活动或片段

     //the data to be passed 
        MyData data =getMyData(); 
        RxBus.getSubject().onNext(data) ; 

3-接收机活动或片段

disposable = RxBus.getSubject(). 
      subscribeWith(new DisposableObserver<Object>() { 


       @Override 
       public void onNext(Object o) { 
        if (o instanceof MyData) { 
        Log.d("tag", (MyData)o.getData(); 
        } 
       } 

       @Override 
       public void onError(Throwable e) { 

       } 

       @Override 
       public void onComplete() { 

       } 
      }); 
    }); 

4退订避免内存leacks:

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    disposable.dispose(); 
}