【问题标题】:Communication between Class and Activity via InterfaceClass 和 Activity 之间通过接口进行通信
【发布时间】:2017-09-14 11:11:12
【问题描述】:

我有MainActivity,想使用接口与类进行通信。

public interface MyInterface(){
    public void doAction();
}

在我的 MainActivity 中我会有这段代码:

public class MainActivity extends AppCompatActivity implements MyInterface(){

    //....some more code here

    @Override
    public void doAction() {
        //any code action here
    }

    //....some more code here

}

那么现在,如果我有另一个类(NOT ACTIVITY),我应该如何正确地在类---接口---mainActivity 之间建立联系??

public class ClassB {

    private MyInterface myinterface;
    //........

    //...... how to initialize the interface
}

我对如何在ClassB中初始化和使用接口感到困惑

【问题讨论】:

    标签: android interface


    【解决方案1】:

    在其他类的构造函数中:ClassB,接受接口作为参数并传递Activity 的引用,将该对象保存在您的Activity 中。

    像这样:

    public class MainActivity extends AppCompatActivity implements MyInterface()
    {
        private ClassB ref; // Hold reference of ClassB directly in your activity or use another interface(would be a bit of an overkill)
    
        @Override
        public void onCreate (Bundle savedInstanceState) {
            // call to super and other stuff....
            ref = new ClassB(this); // pass in your activity reference to the ClassB constructor!
        }
    
        @Override
        public void doAction () {
            // any code action here
        }
    }
    
    public class ClassB
    {
        private MyInterface myinterface;
    
        public ClassB(MyInterface interface)
        {
            myinterface = interface ;
        }
    
        // Ideally, your interface should be declared inside ClassB.
        public interface MyInterface
        {
             // interface methods
        }
    }
    

    仅供参考,这也是 MVP 设计模式中 View 和 Presenter 类的交互方式。

    【讨论】:

    • 谢谢你,你答案中代码的最后一部分是我缺少的部分,它运行良好。
    • @eddie 快乐编码 :)
    【解决方案2】:
    public class MainActivity extends AppCompatActivity implements 
    MyInterface
    {
        OnCreate()
        {
            ClassB classB= new ClassB(this);
        }
    }
    
    public class ClassB
    {
        private MyInterface myinterface;
    
        public ClassB(MyInterface myinterface)
        {
            this.myinterface=myinterface;
        }
    
        void anyEvent() // like user click
        {
            myinterface.doAction();
        }
    }
    

    【讨论】:

      【解决方案3】:
      public class MainActivity extends AppCompatActivity implements MyInterface(){
          private ClassB ref;
      
          @Override
          public void onCreate (Bundle savedInstanceState) {
              ref = new ClassB(); 
              ref.setMyinterface(this);
          }
      
          @Override
          public void doAction () {
              // any code action here
          }
      }
      
      public class ClassB{
          private MyInterface myinterface;
      
          public setMyInterface(MyInterface interface){
            myinterfece = interface;
          }
          public interface MyInterface{
               // interface methods
          }
      }
      

      【讨论】:

        【解决方案4】:

        //-------------------------------------
        //Two way communication using Interface
        //-------------------------------------
        
        //A. Interfaces  
        //Communicator Interface ( Activity to Fragment )
        public interface CommunicateToFragment {
            public void CallBack(String name);
        }
        
        // Communicator Interface ( Fragment to Main )
        public interface CommunicateToMain {
            public void respond(String data);
        }
        
        //B. Main Class implements CommunicateToMain Interface
        //Use CommunicateToFragment interface to send data in FragmentA
        public class MainActivity extends AppCompatActivity implements CommunicateToMain {
            private CommunicateToFragment communicateToFragment;
            
            public void setCommunicateToFragment(CommunicateToFragment communicateToFragment) {
                this.communicateToFragment = communicateToFragment;
            }
        
            @Override
            protected void onCreate (Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
            }
            
            @Override
            public void respond (String data) {
                communicateToFragment.CallBack("Callbacked when onCreate method Created" + data);
                Log.d("test","get result from fragment: " + data);
                FragmentManager manager = getFragmentManager();
                FragmentB f2 = (FragmentB) manager.findFragmentById(R.id.id_fragment2);
                f2.changeText(data);
            }
        }
        
        
        //C. FragmentA implements CommunicateToFragment
        //Use CommunicateToMain interface to send data in MainActivity
        public class FragmentA extends Fragment implements View.OnClickListener, CommunicateToFragment{
            Button button;
            int counter=0;
            CommunicateToMain commToMain;
        
            @Nullable
            @Override
            public View onCreateView (LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
               return inflater.inflate(R.layout.fragment_a,container,false);
            }
        
            @Override
            public void onActivityCreated (@Nullable Bundle savedInstanceState) {
                super.onActivityCreated(savedInstanceState);
                commToMain = (CommunicateToMain) getActivity();
                button = getActivity().findViewById(R.id.button);
                button.setOnClickListener(this);
                if(getActivity() instanceof MainActivity){
                    ((MainActivity) getActivity()).setCommunicateToFragment(this);
                }
            }
        
            @Override
            public void onClick (View view) {
                counter++;
                commToMain.respond("The button was clicked" + counter + " Times");
            }
        
            @Override
            public void CallBack(String name) {
                Log.d("test","get result from main activity: " + name);
            }
        }

        【讨论】:

        • 不鼓励使用纯代码的答案。请单击edit 并添加一些词来总结您的代码如何解决问题,或者解释您的答案与之前的答案/答案有何不同。谢谢
        猜你喜欢
        • 1970-01-01
        • 2019-05-31
        • 1970-01-01
        • 2015-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多