open fragment from fragment code example

Example 1: how to open an activity from a fragment

Button btn1 = (Button) thisLayout
            .findViewById(R.id.btnDb1);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), otherActivity.class);
            ((MainActivity) getActivity()).startActivity(intent);

        }
    });

    return thisLayout;
}

Example 2: change fragment in android studio

// put the following code in onClickListner
// public void onClickListner(View view){
Navigation.findNavController(view).navigate(R.id.action_fromFragment_toFragment);
// action_fromFragment_toFragment is the id of transformatino, look in fragment map.
// }

Example 3: open new fragment from fragment

button.setOnClickListener {
    activity!!
        .supportFragmentManager
        .beginTransaction()
        .replace(R.id.container, NewFragment.newInstance())
        .commitNow()
}

Tags:

Misc Example