how can implement onBackPressed in fragment correctly?

I am developing a new app where I have implemented toolbar as back button in fragment but it is not working as expected.

MedicalDisclaimerFragment:

@SuppressLint("ValidFragment")

class MedicalDisclaimerFragment extends Fragment {

public CustomToolbar customToolbar;

private WebView webView;

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.medical_disclaimer_fragment, container, false);

customToolbar = rootView.findViewById(R.id.toolbar);

customToolbar.setNavigationOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

OnBackPressed();

}

});

webView = rootView.findViewById(R.id.webViewMedical);

webView.loadUrl(getString(R.string.assets_clinical_info));

return rootView;

}

public void onBackPressed() {

CustomToolbar customToolbar;

if (customToolbar != null)

customToolbar.hideHamburger();

else

super.onBackPressed();

}

}

My XML:




android:layout_width="match_parent"

android:layout_height="match_parent"

xmlns:app="http://schemas.android.com/apk/res-auto"

android:orientation="vertical"

android:background="@color/white">


android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="58dp"

app:title="@string/medical_disclaimer"

app:iconNavigate="@drawable/ic_black_back"

app:iconTool="@drawable/ic_menu_20dp" />


android:id="@+id/webViewMedical"

android:layout_gravity="center"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>



Screenshot from layout editor:...

Read More »

By: StackOverFlow - 6 days ago

Related Posts