Transfer the variable from Activity in Fragment



  • Работа программы

    I'm trying to make a schedule, but it's not working. There are two Java Class-a: MainActivity and ContentFragment (containing fragment) made a menu that has two meanings of First Week and Second Week, when the text changes in fragments accordingly.

    I was just trying to give the variable itemPosition meaning.

    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        pos = itemPosition;
        Intent intent = new Intent(MainActivity.this, ContentFragment.class);
        intent.putExtra("pos", pos);
        return true; 
    

    different ways or just getting it in ContentFragment class.

    MainActivity Main = new MainActivity(); 
    int item = Main.pos;
    

    In order to compare it and write the corresponding text if item = 0 - 1 week, if = 1 - 2 but the variable was never obtained. It was constant = 0;

    That's the question: How do you do it? Or maybe there's another simple way to deal with my task before there's no evidence?



  • I will propose such a solution to your task.

    MainActivity

    1. We'll set up an interface:

      interface MainActivityCommunicator{
          void onWeekChanged(int numberOfWeek);
      }
      

      MainActivityCommunicator mSendToFragment;

    2. In method onNavigationItemSelected Add the line:

      public boolean onNavigationItemSelected(int itemPosition, long itemId) {
      ...
      mSendToFragment.onWeekChanged(itemPosition);
      ...
      }

    ContentFragment

    1. We're doing the interface. MainActivityCommunicator

      public class ContentFragment extends ... implements MainActivity.MainActivityCommunicator{
      ...
      @Override
      public void onWeekChanged(int numberOfWeek) {
      //Если выбранная неделя уже отображается, то return
      if(numberOfWeek == mCurrentSelectedWeek){
      return;
      }
      //Тут меняем отображение недели
      }
      ...

      UPD:

    2. Indicate that this fragment is being implemented by this interface:

      @Override
      public void onAttach(Activity activity) {
      super.onAttach(activity);
      Context context = getActivity();
      ((MainActivity) context).mSendToFragment = this;
      }
    3. BothnullI'm referring to the fragment when it becomes Detach:

      @Override
      public void onDetach() {
      super.onDetach();
      Context context = getActivity();
      ((MainActivity) context).mSendToFragment = null;
      }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2