有两个片段A和B,片段A有Textview,片段B有edittext和按钮。 点击FragmentB中的提交需要使用Edittext文本更新FragmentA中的textview。
如何在片段之间进行通信?
答案 0 :(得分:2)
public interface INotifier {
public void notify(Object data);
}
的Utils
public class Utils {
public static INotifier notifier;
}
FragmentA
public FragmentA extends Fragment {
public void onCreateView(...) {
}
public void inSomeMethod() {
if (Utils.notifier != null) {
Utils.notifier.notify(data);
}
}
}
FragmentB
public FragmentB extends Fragment implements INotifier {
public void onCreateView(...) {
Utils.notifier = this;
}
@Override
public void notify(Object data) {
// handle data
}
}
答案 1 :(得分:1)
您需要首先交互活动,这将与第二个片段进行交互。并且还阅读了有关如何操作的文章。
https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
答案 2 :(得分:0)
Fragments
之间的通信是使用Listeners
完成的。如果要更新片段,请使用侦听器告诉MainActivity
按照Google http://developer.android.com/training/basics/fragments/communicating.html的建议更新第二个片段。在Fragment
中创建界面,并在Activity
Fragment中的监听器
public interface FragmentUpdateInterface {
void updateFragment(String newText);
}
@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 = (FragmentUpdateInterface ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentUpdateListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.updateFragment("New Text");
}
<强> MainActivity 强>
在MainActivity
中实现片段为
public static class MainActivity extends Activity
implements MyFragment.FragmentUpdateListener{
public void updateFragment(String newText) {
OtherFragment otherFrag = (OtherFragment)
getSupportFragmentManager().findFragmentById(R.id.other_fragment);
if (otherFrag != null) {
otherFrag.updateFragment(newText);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
OtherFragment otherFrag = new OtherFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
otherFrag.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, otherFrag);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
希望这有帮助。
<强>更新强>
您也可以使用LocalBroadcastManager.getInstance().sendBroadcast()
通知另一个片段。