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)
Bundle bundle=this.getArguments()
String b=bundle.getString("zhu")
a.setText(b)