简体   繁体   中英

Android Studio How do I pass data from fragment to fragment when a navigation view is being used?

So I'm using a navigation view and I was trying to see how I could pass data from fragment to fragment. I ask this because I never have a place where a reference is made for any of the fragments inside the main activity nor in between the fragments. Here is the code from the main activity:

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {


    private DrawerLayout drawer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();


        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragmentHolder,
                    new Fragment1()).commit();
            navigationView.setCheckedItem(R.id.nav_frag1);

        }

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.nav_frag1:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragmentHolder,
                        new Fragment1()).commit();

                break;
            case R.id.nav_frag2:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragmentHolder,
                        new frag2()).commit();

                break;
            case R.id.nav_frag3:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragmentHolder,
                        new Fragment3()).commit();

                break;

            case R.id.nav_action1:

                    getSupportFragmentManager().findFragmentById(R.id.fragmentHolder).setArguments(bundle);
                } else {

                }
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


}

I've tried to use bundles, but it doesn't seem like I can get a reference to the frags I'm trying to get to. I'm also trying to figure out how to make action_1 pass a boolean into fragment 1. I've also tried to use an interface, but that hasn't worked for me either. I'm pretty new so I'm hoping there is a way to do this. Any suggestions? Thanks!

You can declare and instantiate a ViewModel class (or more than one really) that's tied to the FragmentActivity scope that's housing your Fragments.

    model = activity?.run { ViewModelProviders.of(this)[SharedViewModel::class.java]

If you do the same in the Fragments and assuming the parameter you pass is the same FragmentActivity that houses the Fragment then you'll get the same ViewModel instance. Since the ViewModel instance is shared between the Activity and the Fragments, you can use it to pass data between them. And since it's a custom class that just extends ViewModel you store whatever you need in them.

Here's a link to the official docs: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM