1. 程式人生 > >EventBus 3.0的使用

EventBus 3.0的使用

前提條件:Evenbus,必須註冊,並且在傳送頁面和接收頁面都得有公共的方法,要實現的效果

程式碼 比較簡單,這裡貼出一些關鍵程式碼(至於安裝可以使用Jar和依賴來進行安裝),我這裡頁面銷燬沒有登出,大家使用的時候登出一下

Fragment_one.java
public class Fragment_one  extends Fragment {
    Button mButton;
    int index=0;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = (View)inflater.inflate(R.layout.fragment_one,null);
         mButton  = (Button)view.findViewById(R.id.btn);
        //關鍵程式碼,必須註冊
        EventBus.getDefault().register(this);
         return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                index++;
                //傳送廣播
                EventBus.getDefault().post(new EvenbusBean(index));

            }
        });

    }
    //公共方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void  Changed(EvenbusBean event){ }
}
EvenbusBean.java
public class EvenbusBean {
    public  int index;
    public EvenbusBean(int index) {
        this.index = index;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}

在Fragment_two中進行接收

public class Fragment_two extends Fragment {
    
    private TextView tv;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //必須註冊
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = (View)inflater.inflate(R.layout.fragment_two,null);
        tv  = (TextView)view.findViewById(R.id.tv);
        return view;
        }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    //接收Evebbus
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void change(EvenbusBean event){

        int a = event.getIndex();
        Log.i("520it","a1="+a);
        tv.setText("點選次數="+a);


    }


}