如何使用AndroidX导航组件将click事件从片段传递到Container活动?

时间:2020-06-02 07:10:52

标签: android android-fragments android-architecture-navigation

我想将按钮单击事件从片段传递到其容器活动,我正在使用Android Jetpack导航。当要在片段中按下按钮时,我想显示Container活动的底部。

这是容器活动-

public class MainScreenActivity extends AppCompatActivity {

    private CardView mButtomSheet;
    private BottomSheetBehavior bottomSheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_screen);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
      //  NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        // To hide Appp Bar
        NavigationUI.setupWithNavController(navView, navController);

        mButtomSheet = findViewById(R.id.mybuttom_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(mButtomSheet);


    }

}

按钮所在的我的片段代码-

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private EditText searchInput;
    private RecyclerView booksRv;
    private BooksAdapter adapter;
    private ImageView loadingImg;
    private Button btnShowDetails;

    public static final String TAG = "HomeFragment";
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        searchInput = root.findViewById(R.id.search_input);
        booksRv = root.findViewById(R.id.books_rv);
        loadingImg = root.findViewById(R.id.loading_image);
        btnShowDetails  = root.findViewById(R.id.show_details); 
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //view model
        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);

        btnShowDetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Need to call some event in Container activity
            }
        });

    }
}

0 个答案:

没有答案