如何从另一个片段访问片段对象

ash*_*awe 5 android fragment android-fragments android-studio android-recyclerview

我有一个导航抽屉活动(Supervisor Dashboard),其中我有一个具有 recyclerview 的片段(工作人员详细信息)。

在同一个活动中,我有一个显示排序选项的底部工作表片段。

现在,我想将用户选择的那些排序选项应用到 RecyclerView。

Activity -> Fragment1 (worker details) -> RecyclerView
                                       -> RecyclerViewAdapter
                                       -> RecyclerViewModel
         -> Fragment2 (bottom sheet)   -> Sort options
Run Code Online (Sandbox Code Playgroud)

那么,如何访问 Fragment1 的 RecyclerView 对象并从 Fragment2 中的 onClick 对适配器的数组进行排序

现在,我已经可以通过使用从片段调用主机活动方法

(SupervisorDashboard)getActivity()).method()
Run Code Online (Sandbox Code Playgroud)

但是如何从主机活动访问 Fragment1 的 RecyclerView 对象?

工人详情

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

主管仪表板

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

我可以在 Fragment2 中创建一个静态方法,然后从 Fragment1 调用该方法,但必须有一些正确的方法来做到这一点。

Bha*_*wal 1

样本片段

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;
}
Run Code Online (Sandbox Code Playgroud)

一旦在 MainActivity 或任何其他想要从 Fragment 访问 TextView/Button 的地方完成此操作,您应该确保在 OnCreate() 方法中设置片段,否则很可能会抛出 nullPointer。因此,您想要更改 TextView/Button 的活动应该如下所示:

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
Run Code Online (Sandbox Code Playgroud)