Fragment和Activity的通信

Fragment和Activity的通信

Fragment傳輸到Activity

  • 一、因爲fragment中不能直接用findViewById方法,只能通過View方法轉換。
  View view= inflater.inflate(R.layout.fragment_yellow, container, false);
  button=view.findViewById(R.id.bt_tz);
  return view;
  • 二、在按鈕上添加監聽事件,且傳值
 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  MainActivity mainActivity=new MainActivity();
                 mainActivity.text("顯示");
            }
        });
  • 三、在activity中,添加一個TextView,用來接收fragment傳輸的數據。
  <TextView
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:id="@+id/tvname"
        />
 text=findViewById(R.id.tvname);
 public  void  text(String gg){
        text.setText(gg);
    }

Activity傳輸到Fragment

  • 一、在activity中創建Bunder,幷包裹數據傳到fragment中
  Bundle bundle=new Bundle();
  bundle.putString("zhu","豬頭");
  yellowFragment.setArguments(bundle);
  • 二、在fragment中接收
  Bundle bundle=this.getArguments();
        String b=bundle.getString("zhu");
        a.setText(b);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章