简体   繁体   English

如何在两个片段之间传递字符串值?

[英]How to pass String Value between two fragments?

I am developing an application which consists of three Fragment under a single Activity : 我正在开发一个应用程序,该应用程序在一个Activity下包含三个Fragment

1.Fragment(1) consist of Text-views. 1.Fragment(1)包含文本视图。
2.Fragment(2) consist of Edit text. 2.Fragment(2)由编辑文本组成。

Here is my problem: 这是我的问题:

When TextView is selected in fragment(1), that TextView value should be passed to the EditText present in fragment(2). 在fragment(1)中选择TextView ,该TextView值应传递给fragment(2)中存在的EditText

public class OrdersActivity extends Activity {

    private Bundle bundle;
    private ArrayList<String> eList;

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

        bundle = new Bundle();
        bundle.putStringArrayList("elist", eList);


        FragmentTransaction order = getFragmentManager().beginTransaction();
        OrdersList orderList = new OrdersList();
        orderList.setArguments(bundle);
        order.add(R.id.frmOrderlist, orderList);
        order.commit();

        FragmentTransaction input = getFragmentManager().beginTransaction();
        InputEdit inputEdit = new InputEdit();
        input.add(R.id.frmOrderinput, inputEdit);
        input.commit();

        FragmentTransaction quoteorder = getFragmentManager().beginTransaction();
        QuoteFragment quotefragment = new QuoteFragment();
        quoteorder.add(R.id.frmSecondList, quotefragment);
        quoteorder.commit();


        FragmentTransaction quotechart = getFragmentManager().beginTransaction();
        ChartOrderFragment chartquote = new ChartOrderFragment();
        quotechart.add(R.id.frmOrderChart, chartquote);
        quotechart.commit();

    }

The good approach is to use Activity as a dispatcher to communicate fragments each other. 好的方法是将Activity用作调度程序,以相互交流片段。

  1. Create a custom listener in Fragment1. 在Fragment1中创建一个自定义侦听器。 Invoke a listener's method if text view is selected in fragment. 如果在片段中选择了文本视图,则调用侦听器的方法。
  2. Create a method like setCustomtext in Fragment2 to update text. 在Fragment2中创建类似setCustomtext的方法来更新文本。
  3. Inside activity create a listener implementation and register it in Fragment1. 内部活动创建一个侦听器实现,并将其注册到Fragment1中。 This listener will be invoked when text changed and the invoke a setCustomtext method in Fragment2. 更改文本后将调用此侦听器,并在Fragment2中调用setCustomtext方法。

Please see the following link Communicating with the Activity 请参阅以下链接与活动进行通信

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM