*/Android

[안드로이드] Activity, Fragment 간 데이터 주고받기

sssbin 2022. 10. 21. 16:23

 

Activity -> Activity 

// LoginActivity (온클릭리스너 안에)

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("nickname", res.getMessage());
startActivity(intent);
// MainActivity (온크리에이트 안에)

Intent intent = getIntent();
String username = intent.getStringExtra("nickname");

 

Activity -> Fragment 

// MainActivity

binding.btnWatch.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        TodoFragment fragment_watch = new WatchFragment();

	/****** 값 보내는 부분 ******/
        Bundle bundle = new Bundle();
        bundle.putString("username", username);
        fragment_watch.setArguments(bundle);
	/************************/

        transaction.replace(R.id.frame,fragment_watch);
        transaction.commit();
}
// WatchFragment

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentWatchBinding.inflate(inflater, container, false);
        
	...
	/****** 값 받아오는 부분 ******/
        String username = getArguments().getString("username");
	/**************************/
	...
    
        return binding.getRoot();
}