每日一道面試題(第2期)---Activity 與 Fragment 之間常見的幾種通訊方式?

零零碎碎的東西老是記不長久,僅僅學習別人的文章也只是他人咀嚼後留下的殘渣。無心中發現了這個每日一道面試題,想了想若是隻是簡單地去思考,那麼不只會收效甚微,甚至難一點的題目本身可能都懶得去想,堅持不下來。因此不如把每一次的思考、理解以及別人的看法記錄下來。不只加深本身的理解,更要激勵本身堅持下去。java

參數傳遞

若是是在創建Fragment時須要Activity中的一些數據做爲初始化,那麼能夠經過Activity中的setArguments(bundle)方法傳遞參數,在Fragment中經過getArguments得到Bundle對象來解析參數。git

public class MainActivity extends BaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Fragment firstFragment = new FirstFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", "數據");
        
        //顯示Fragment
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.fragment, firstFragment).show(firstFragment).commit();
    }
}
public class FirstFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        Bundle bundle = getArguments();
        String data = bundle.getString("data");
        return view;
    }
}
複製代碼

數據傳遞、事件監聽

若是是建立後須要進行通訊,那能夠經過接口回調、廣播、eventbus來進行。這些均可以是雙向的,只是看你怎麼設置。如下例子皆監聽Fragment中的事件。github

接口回調

在Fragment中面試

public class FirstFragment extends Fragment {
    private OnFragmentInteractionListener mListener;
    private Button button;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        button = view.findViewById(R.id.bt_fragment);
        button.setOnClickListener(v -> mListener.onFragmentInteraction("接口發送消息啦"));

        return view;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //綁定Activity
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }
    //解綁activity時設爲null
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    
    //自定義一個接口
    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(String str);
    }
}
複製代碼

在Activity中實現OnFragmentInteractionListener接口重寫onFragmentInteraction方法就能夠了框架

public class MainActivity extends BaseActivity implements FirstFragment.OnFragmentInteractionListener {
    @Override
    public void onFragmentInteraction(String str) {
        Toast.makeText(this, "接口收到通知啦", Toast.LENGTH_SHORT).show();
    }
}
複製代碼

廣播

在Activity中註冊廣播ide

public class MainActivity extends BaseActivity implements FirstFragment.OnFragmentInteractionListener {
    //處理事件
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case BROADCAST_ACTION:
                    Toast.makeText(context, "收到通知啦", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //註冊廣播
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.goldenhamster.myboradcastreceiver");
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //記得取消註冊
        unregisterReceiver(receiver);
    }
}
複製代碼

在Fragment中發送廣播post

public class FirstFragment extends Fragment {

    private Button button;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        button = view.findViewById(R.id.bt_fragment);
        button.setOnClickListener(v -> getActivity().sendBroadcast(new Intent("com.goldenhamster.myboradcastreceiver")));
        return view;
    }
}
複製代碼

EventBus框架

設置信息類學習

public class EventUtil {
    private String mes;
    public EventUtil(String mes){
        this.mes = mes;
    }
    public String getMes() {
        return mes;
    }
}
複製代碼

在Activity中註冊監聽EventBusthis

public class MainActivity extends BaseActivity{
    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    //使用註解標記事件處理方法
    @Subscribe
    public void onEvent(EventUtil event){
        if(event.getMes().equals("data")){
            Toast.makeText(context, "收到通知啦", Toast.LENGTH_SHORT).show();
        }
    }
}
複製代碼

在Fragment中發送消息spa

public class FirstFragment extends Fragment {
    private Button button;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        button = view.findViewById(R.id.bt_fragment);
        button.setOnClickListener(v -> EventBus.getDefault().post(new EventUtil("data")));
        return view;
    }
}
複製代碼
相關文章
相關標籤/搜索