可以通过使用接口在Activity和Fragment之间进行通信和数据共享。以下是示例代码:
public interface MyListener {
void onDataReceived(String data);
}
public class MainActivity extends AppCompatActivity implements MyListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment fragment = new MyFragment();
fragment.setListener(this); // 注册接口
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
@Override
public void onDataReceived(String data) {
// 从Fragment接收数据
Log.d("MainActivity", "Received data: " + data);
}
}
public class MyFragment extends Fragment {
private MyListener mListener;
public void setListener(MyListener listener) {
mListener = listener;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyListener) {
mListener = (MyListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement MyListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void sendDataToActivity(String data) {
if (mListener != null) {
mListener.onDataReceived(data);
}
}
}