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)