How to pass values from a Class to Activity - Android

前端 未结 6 1260
误落风尘
误落风尘 2021-02-09 08:23

I have a newbie question about Class/Task/Activity. I\'m coming from C so I don\'t know if it\'s a good approach to do what I need.

I\'ve created a class:



        
6条回答
  •  不知归路
    2021-02-09 08:40

    You have an A activity and B one, when you finish actions on B activity side you need it to effect A side when you come back.

    1. Create an Instance Class and a method that u type u need, let's say;

      public interface SelectedBirthday {
      
          void onSelectedData(String date);
      }
      
    2. Now we are on B side, Create an instance of your Interface Class

      private SelectedBirthday mCallback;
      
    3. Override

      @Override
      public void onAttach(Activity activity) {
          super.onAttach(activity);
      
          try {
              mCallback = (SelectedBirthday) activity;
          } catch (ClassCastException e) {
              Log.d("MyDialog", "Activity doesn't implement the ISelectedData interface");
          }
      }
      
    4. Now upload the value you needed

      String userBirth = (day + " " + month + " " + year);
      
      mCallback.onSelectedData(userBirth);
      
    5. Ok let's go to A side

    Implement our Interface Class

    implements SelectedBirthday
    

    it will warn you for its method and you implemented it

         @Override
            public void onSelectedData(String date) {
                if (!date.equals("")) {
                    txt_poup_age.setText(date);
    //now you are free to do what you want with the value you received automaticaly
                }
            }
    

提交回复
热议问题