Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a fragment object from another fragment

I have a navigation drawer activity(Supervisor Dashboard) in which I have a fragment (worker details) having recyclerview.

In the same activity, I have a bottom sheet fragment which displays sorting options.

Now, I want to apply those sorting options user selected to the RecyclerView.

Activity -> Fragment1 (worker details) -> RecyclerView
                                       -> RecyclerViewAdapter
                                       -> RecyclerViewModel
         -> Fragment2 (bottom sheet)   -> Sort options

So, how do I access the Fragment1's RecyclerView object and sort the adapter's array from the onClick in the Fragment2

Now, I can already call a host activity method from the fragment by using

(SupervisorDashboard)getActivity()).method()

But how do I access RecyclerView object of Fragment1 from host activity?

Worker Details

public class WorkerDetailsFragment extends Fragment {

    private WorkerDetailsViewModel workerDetailsViewModel;
    static RecyclerView recyclerView;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        workerDetailsViewModel = ViewModelProviders.of(this).get(WorkerDetailsViewModel.class);
        View root = inflater.inflate(R.layout.fragment_worker_details, container, false);

        recyclerView = root.findViewById(R.id.rc_worker_details);
        WorkerRVAdapter workerRVAdapter = new WorkerRVAdapter(
                workerDetailsViewModel.getWorkerNames(),
                workerDetailsViewModel.getWorkerRoles(),
                workerDetailsViewModel.getImageUrls(),
                getContext());
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(workerRVAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        return root;
    }
}

SupervisorDashboard

public class SupervisorDashboard extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_supervisor_dashboard);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.supervisor_dashboard, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                View view = getLayoutInflater().inflate(R.layout.fragment_bottom_sheet_sort, null);

//                BottomSheetDialog dialog = new BottomSheetDialog(this);
//                dialog.setContentView(view);
//                dialog.show();
                BottomSheetSortFragment bottomSheetFragment = new BottomSheetSortFragment();
                bottomSheetFragment.show(getSupportFragmentManager(), "hello");
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

BottomSheetSortFragment

public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bottom_sheet_sort, container, false);

        button = view.findViewById(R.id.apply_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Sort the arrays in RecyclerView on click
                dismiss();
            }
        });

        return view;
    }

I can create a static method in Fragment2 and then call that method from Fragment1 but there has to be some proper way of doing it.

like image 330
ashawe Avatar asked Nov 06 '22 14:11

ashawe


1 Answers

Sample Fragment

public class SomeFragment extends Fragment {
public View view;
public TextView textView;
public Button button;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view =inflater.inflate(R.layout.fragment_blank, container, false);
    textView = (TextView)view.getRootView().findViewById(R.id.textView_fragment1);
    return view;
}

public void getTextView(){
    return textView;
}

public void getButton(){
    return button;
}

Once that is done in your MainActivity or any other where you want to access your TextView/Button from your Fragment you should make sure to set up the fragment in your OnCreate() method other ways it will most likely throw nullPointer. So your activity where you want to change the TextView/Button should look smth like this:

public class MainActivity extends AppCompatActivity {
private Button button1;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
SomeFragment someFragment = new SomeFragment();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1 = (Button)findViewById(R.id.button1);
    changeFragment();

    fragmentManager = getFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1,someFragment);
    fragmentTransaction.commit();

    // Now we can get access to TextView and Button inside SomeFragment
}

public void updateText(String msg) {
    TextView v = this.someFragment.getTextView();
    v.setText(msg);
}

} // end of activity
like image 91
Bharat Biswal Avatar answered Nov 14 '22 21:11

Bharat Biswal