75

我有一项活动 - MainActivity。在这个活动中,我有两个片段,这两个片段都是我在 xml 中以声明方式创建的。

我正在尝试将String用户输入的文本传递Fragment AFragment B. 然而,事实证明这是非常困难的。有谁知道我如何做到这一点?

我知道片段可以使用getActivity(). 所以我猜我会从那里开始?

4

14 回答 14

126

看看 Android 开发者页面:http: //developer.android.com/training/basics/fragments/communicating.html#DefineInterface

基本上,您在 Fragment A 中定义一个接口,并让您的 Activity 实现该接口。现在你可以在你的 Fragment 中调用接口方法,你的 Activity 就会收到这个事件。现在在您的活动中,您可以调用您的第二个片段以使用接收到的值更新文本视图

您的 Activity 实现了您的界面(参见下面的 FragmentA)

public class YourActivity implements FragmentA.TextClicked{
    @Override
    public void sendText(String text){
        // Get Fragment B
        FraB frag = (FragB)
            getSupportFragmentManager().findFragmentById(R.id.fragment_b);
        frag.updateText(text);
    }
}

Fragment A定义了一个Interface,需要的时候调用该方法

public class FragA extends Fragment{

    TextClicked mCallback;

    public interface TextClicked{
        public void sendText(String text);
    }

    @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 = (TextClicked) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
        }
    }

    public void someMethod(){
        mCallback.sendText("YOUR TEXT");
    }

    @Override
    public void onDetach() {
        mCallback = null; // => avoid leaking, thanks @Deepscorn
        super.onDetach();
    }
}

片段 B 有一个公共方法来处理文本

public class FragB extends Fragment{

    public void updateText(String text){
        // Here you have it
    }
}
于 2012-12-04T10:41:50.027 回答
35

其他一些示例(甚至在撰写本文时的文档)使用过时的onAttach方法。这是一个完整更新的示例。

在此处输入图像描述

笔记

  • 您不希望 Fragments 直接相互交谈或与 Activity 交谈。这将它们与特定的 Activity 联系在一起,使重用变得困难。
  • 解决方案是制作一个Activity将实现的回调监听器接口。当 Fragment 想要向另一个 Fragment 或其父 Activity 发送消息时,它可以通过接口来完成。
  • Activity 可以直接与其子片段公共方法通信。
  • 因此,Activity 充当控制器,将消息从一个片段传递到另一个片段。

代码

MainActivity.java

public class MainActivity extends AppCompatActivity implements GreenFragment.OnGreenFragmentListener {

    private static final String BLUE_TAG = "blue";
    private static final String GREEN_TAG = "green";
    BlueFragment mBlueFragment;
    GreenFragment mGreenFragment;

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

        // add fragments
        FragmentManager fragmentManager = getSupportFragmentManager();

        mBlueFragment = (BlueFragment) fragmentManager.findFragmentByTag(BLUE_TAG);
        if (mBlueFragment == null) {
            mBlueFragment = new BlueFragment();
            fragmentManager.beginTransaction().add(R.id.blue_fragment_container, mBlueFragment, BLUE_TAG).commit();
        }

        mGreenFragment = (GreenFragment) fragmentManager.findFragmentByTag(GREEN_TAG);
        if (mGreenFragment == null) {
            mGreenFragment = new GreenFragment();
            fragmentManager.beginTransaction().add(R.id.green_fragment_container, mGreenFragment, GREEN_TAG).commit();
        }
    }

    // The Activity handles receiving a message from one Fragment
    // and passing it on to the other Fragment
    @Override
    public void messageFromGreenFragment(String message) {
        mBlueFragment.youveGotMail(message);
    }
}

GreenFragment.java

public class GreenFragment extends Fragment {

    private OnGreenFragmentListener mCallback;

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

        Button button = v.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = "Hello, Blue! I'm Green.";
                mCallback.messageFromGreenFragment(message);
            }
        });

        return v;
    }

    // This is the interface that the Activity will implement
    // so that this Fragment can communicate with the Activity.
    public interface OnGreenFragmentListener {
        void messageFromGreenFragment(String text);
    }

    // This method insures that the Activity has actually implemented our
    // listener and that it isn't null.
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnGreenFragmentListener) {
            mCallback = (OnGreenFragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnGreenFragmentListener");
        }
    }

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

BlueFragment.java

public class BlueFragment extends Fragment {

    private TextView mTextView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_blue, container, false);
        mTextView = v.findViewById(R.id.textview);
        return v;
    }

    // This is a public method that the Activity can use to communicate
    // directly with this Fragment
    public void youveGotMail(String message) {
        mTextView.setText(message);
    }
}

XML

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <!-- Green Fragment container -->
    <FrameLayout
        android:id="@+id/green_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_marginBottom="16dp" />

    <!-- Blue Fragment container -->
    <FrameLayout
        android:id="@+id/blue_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

片段绿色.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:background="#98e8ba"
              android:padding="8dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:text="send message to blue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

片段蓝色.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:background="#30c9fb"
              android:padding="16dp"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview"
        android:text="TextView"
        android:textSize="24sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
于 2017-10-23T14:48:40.943 回答
14

最好和推荐的方法是使用共享 ViewModel。

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

来自谷歌文档:

public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

public void select(Item item) {
    selected.setValue(item);
}

public LiveData<Item> getSelected() {
    return selected;
}
}


public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    itemSelector.setOnClickListener(item -> {
        model.select(item);
    });
}
}


public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
    model.getSelected().observe(this, { item ->
       // Update the UI.
    });
}
}

ps:两个片段从不直接通信

于 2018-06-05T00:30:37.990 回答
4

考虑我的 2 个片段 A 和 B,假设我需要将数据从 B 传递到 A。

然后在 B 中创建一个接口,并将数据传递给 Main Activity。在那里创建另一个接口并将数据传递给片段 A。

分享一个小例子:

片段 A 看起来像

public class FragmentA extends Fragment implements InterfaceDataCommunicatorFromActivity {
public InterfaceDataCommunicatorFromActivity interfaceDataCommunicatorFromActivity;
String data;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return super.onCreateView(inflater, container, savedInstanceState);
}

@Override
public void updateData(String data) {
    // TODO Auto-generated method stub
    this.data = data;
    //data is updated here which is from fragment B
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    try {
        interfaceDataCommunicatorFromActivity = (InterfaceDataCommunicatorFromActivity) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
    }

}

}

片段B看起来像

class FragmentB extends Fragment {
public InterfaceDataCommunicator interfaceDataCommunicator;

@Override
public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    // call this inorder to send Data to interface
    interfaceDataCommunicator.updateData("data");
}

public interface InterfaceDataCommunicator {
    public void updateData(String data);
}

@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    try {
        interfaceDataCommunicator = (InterfaceDataCommunicator) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
    }

}

}

主要活动是

public class MainActivity extends Activity implements InterfaceDataCommunicator {
public InterfaceDataCommunicatorFromActivity interfaceDataCommunicatorFromActivity;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void updateData(String data) {
    // TODO Auto-generated method stub
    interfaceDataCommunicatorFromActivity.updateData(data);

}

public interface InterfaceDataCommunicatorFromActivity {
    public void updateData(String data);
}

}
于 2013-10-30T09:59:31.270 回答
3

片段之间有多种通信方式。

于 2021-07-06T07:09:58.603 回答
1

有一种简单的方法可以使用架构组件实现活动片段之间的通信。可以使用 ViewModel 和 LiveData 在活动的片段之间传递数据。

参与通信的片段需要使用与活动生命周期相关的相同视图模型对象。视图模型对象包含 livedata 对象,数据由一个片段传递到该对象,第二个片段侦听 LiveData 上的更改并接收从片段一发送的数据。

有关完整示例,请参见http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel

于 2018-08-18T15:58:56.490 回答
0

学习“setTargetFragment()”

其中“ startActivityForResult() ”建立了 2 个活动之间的关系,“ setTargetFragment() ”定义了 2 个片段之间的调用者/被调用者关系。

于 2018-08-18T20:06:10.173 回答
0

我为我的活动提供了一个所有片段都可以使用的界面。如果您在同一个活动上有许多片段,这可以节省大量代码重写,并且比为具有相似功能的每个片段制作单独的界面更清洁/更模块化。我也喜欢它的模块化方式。不利的一面是,一些片段可以访问他们不需要的功能。

    public class MyActivity extends AppCompatActivity
    implements MyActivityInterface {

        private List<String> mData; 

        @Override
        public List<String> getData(){return mData;}

        @Override
        public void setData(List<String> data){mData = data;}
    }


    public interface MyActivityInterface {

        List<String> getData(); 
        void setData(List<String> data);
    }

    public class MyFragment extends Fragment {

         private MyActivityInterface mActivity; 
         private List<String> activityData; 

         public void onButtonPress(){
              activityData = mActivity.getData()
         }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if (context instanceof MyActivityInterface) {
                mActivity = (MyActivityInterface) context;
            } else {
                throw new RuntimeException(context.toString()
                        + " must implement MyActivityInterface");
            }
        }

        @Override
        public void onDetach() {
            super.onDetach();
            mActivity = null;
        }
    } 
于 2019-08-14T15:33:01.670 回答
0

您可以使用 2 方法在 2 之间进行通信fragments

1)

可以LiveData用来观察一个fragment在另一个的数据变化

创建共享 ViewModel

public class SharedViewModel extends ViewModel {

private MutableLiveData<String> name;

public void setNameData(String nameData) {
    name.setValue(nameData);
}

public MutableLiveData<String> getNameData() {
    if (name == null) {
        name = new MutableLiveData<>();
    }

    return name;
}
}

片段一

 private SharedViewModel sharedViewModel;

 public FragmentOne() {

 }

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
     submitButton.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

            sharedViewModel.setNameData(submitText.getText().toString());
           }
      });

 }

片段二

 private SharedViewModel sharedViewModel;

 public FragmentTwo() {

 }

 @Override
 public void onCreate(@Nullable Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     sharedViewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

     sharedViewModel.getNameData().observe(this, nameObserver);
 }

 Observer<String> nameObserver = new Observer<String>() {
    @Override
    public void onChanged(String name) {
       receivedText.setText(name);
    }
 };

有关 viewmodel 的更多详细信息,您可以参考:mvvm-viewmodel-livedata通信片段

2)

您可以使用eventbus来实现相同的目的

implementation 'org.greenrobot:eventbus:3.2'

定义事件

public static class MessageEvent { /* Additional fields if needed */ }

注册/注销订阅者

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

收听事件

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

发布活动

 EventBus.getDefault().post(new MessageEvent());
于 2021-10-07T08:37:37.120 回答
0

从 Fragment 1.3.0 开始,我们提供了一种在 Fragment 之间进行通信的新方式。

从 Fragment 1.3.0 开始,每个 FragmentManager 都实现了 FragmentResultOwner。这意味着 FragmentManager 可以充当片段结果的中央存储。此更改允许组件通过设置块结果并侦听这些结果来相互通信,而无需这些组件相互直接引用。

片段监听器:

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Use the Kotlin extension in the fragment-ktx artifact
setFragmentResultListener("requestKey") { requestKey, bundle ->
    // We use a String here, but any type that can be put in a Bundle is supported
    val result = bundle.getString("bundleKey")
    // Do something with the result
 }
}

片段发射器:

button.setOnClickListener {
val result = "result"
// Use the Kotlin extension in the fragment-ktx artifact
setFragmentResult("requestKey", bundleOf("bundleKey" to result))
}
于 2021-11-16T15:24:49.937 回答
0

基本上,以下是两个片段之间的通信方式:

i) ViewModel
ii) Fragment Result API
iii) Interface
于 2022-02-02T12:29:57.863 回答
-1

更新

忽略这个答案。并不是说它不起作用。但是有更好的方法可用。此外,Android 强烈反对 Fragment 之间的直接通信。见官方文档。感谢用户@Wahib Ul Haq 的提示。

原始答案

好吧,您可以在 Fragment B 中创建一个私有变量和 setter,并从 Fragment A 本身设置值,

片段B.java

private String inputString;
....
....

public void setInputString(String string){
   inputString = string;
}

片段A.java

//go to fragment B

FragmentB frag  = new FragmentB();
frag.setInputString(YOUR_STRING);
//create your fragment transaction object, set animation etc
fragTrans.replace(ITS_ARGUMENTS)

或者您可以按照您的建议使用 Activity ..

于 2012-12-04T10:33:05.227 回答
-1

我最近创建了一个库,它使用注释为您生成那些类型转换样板代码。 https://github.com/zeroarst/callbackfragment

这是一个例子。单击一个TextViewonDialogFragment触发回调MainActivityonTextClicked然后获取MyFagment要与之交互的实例。

public class MainActivity extends AppCompatActivity implements MyFragment.FragmentCallback, MyDialogFragment.DialogListener {

private static final String MY_FRAGM = "MY_FRAGMENT";
private static final String MY_DIALOG_FRAGM = "MY_DIALOG_FRAGMENT";

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

    getSupportFragmentManager().beginTransaction()
        .add(R.id.lo_fragm_container, MyFragmentCallbackable.create(), MY_FRAGM)
        .commit();

    findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyDialogFragmentCallbackable.create().show(getSupportFragmentManager(), MY_DIALOG_FRAGM);
        }
    });
}

Toast mToast;

@Override
public void onClickButton(MyFragment fragment) {
    if (mToast != null)
        mToast.cancel();
    mToast = Toast.makeText(this, "Callback from " + fragment.getTag() + " to " + this.getClass().getSimpleName(), Toast.LENGTH_SHORT);
    mToast.show();
}

@Override
public void onTextClicked(MyDialogFragment fragment) {
    MyFragment myFragm = (MyFragment) getSupportFragmentManager().findFragmentByTag(MY_FRAGM);
    if (myFragm != null) {
        myFragm.updateText("Callback from " + fragment.getTag() + " to " + myFragm.getTag());
    }
}

}

于 2017-05-30T04:56:34.647 回答