2016-02-09 6 views
1

enter image description hereКак обновить представление в фрагменте из фрагмента ребенка в андроиде

Есть два фрагмента А и В, фрагменте А имеет TextView и фрагмент B имеет EditText и кнопку. Нажмите, чтобы отправить в FragmentB необходимо обновить текст в FragmentA с текстом Edittext.

Как сделать связь между фрагментом?

+0

пытаются аннулировать TextView в фрагмент с обратным вызовом. – Sreekanth

+0

Есть две возможности использования интерфейса между этими фрагментами, или вы можете использовать библиотеку Eventbus, которая позволяет вам создавать локальные события и прослушиватели событий для этого. Если вам нужно больше на eventbus, дайте мне знать. – androidnoobdev

+1

Вы должны добавить слушателя и посмотреть на это http://developer.android.com/intl/ja/training/basics/fragments/communicating.html –

ответ

2

n этот пример, уведомление об ошибке FragmentA. INotifier

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 
    } 
} 
0

Связь между Fragments осуществляется usinng Listeners. Если вы хотите обновить фрагмент, используйте прослушиватель, чтобы сообщить MainActivity, чтобы обновить второй фрагмент, как рекомендовано Google http://developer.android.com/training/basics/fragments/communicating.html. Создание интерфейса в Fragment и реализовать это в Activity

Listener в Фрагменте

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(); 
     } 
    } 

Надеется, что это помогает.

UPDATE:

Вы также можете использовать LocalBroadcastManager.getInstance().sendBroadcast() уведомить к другому фрагменту, а также.

+0

его выдача циклического вопроса наследования –

+0

Используете ли вы какой-либо другой интерфейс, который реализуется во Фрагменте? –

+0

Да, я использую вкладку смены списков ... проверьте мой ответ –

Смежные вопросы