How to Send data from activity to fragment in Android Studio?
- In your
Activity
, create a newBundle
object and add the value you want to pass to theFragment
.
MyActivity.java
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Create a new bundle object and add the value to pass to the fragment
Bundle bundle = new Bundle();
String valueToPass = "Hello, Fragment!";
bundle.putString("key", valueToPass);
// Create a new instance of the fragment and set the arguments to the bundle
MyFragment myFragment = new MyFragment();
myFragment.setArguments(bundle);
// Load the fragment into the container
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, myFragment)
.commit();
}
}
Fragment.java
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
// Retrieve the value from the bundle
String value = getArguments().getString("key");
// Use the value as needed
TextView textView = view.findViewById(R.id.text_view);
textView.setText(value);
return view;
}
}
if You user onOptionsItemSelected
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// Handle item selection
switch (id) {
case R.id.action_search:
// Do something when the "Settings" item is clicked
Toast.makeText(this,"action_settings",Toast.LENGTH_LONG).show();
return true;
case R.id.action_reg:
Intent reg = new Intent(MainActivity.this, Log_Reg.class);
startActivity(reg);
finish();
return true;
case R.id.action_cart:
// Bundle bundle = new Bundle();
// bundle.putString("userID", useID);
Fragment fragment = new AddToCart();
// fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_host_fragment_content_main, fragment).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}