open fragment from onOptionsItemSelected , in navigation drawer, fragment overlap and stay - fragment

Bonjour,
In Android Studio, I am trying to open a fragment from the onOptionsItemSelected in a navigationdrawer, it opens the frgament but the fragment will ovelap the one who was there and it remains there.
so now when I call another fragmentit will be shown at the back so I will have many occurencse of the fragment overlapping.
I hope I am clear
this is the code i use in the MainActivity to call the fragment from onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.action_apropos:e:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment_content_main,
new AnnoncesFragment(),null).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
if I use this code:
NavController navController = Navigation.findNavController(this,
R.id.nav_host_fragment_content_main);
navController.navigate(R.id.nav_apropos);
everything works fine but I will not be abble to pass arguments
Thanks for your help

Related

button back to my app in the background and when you resume it starts again

I am developing an app in Xamarin.Forms, before I was trying to make a master detail page to become my MainPage when I logged in to my app, this I have already achieved. Now I have the problem that when I use the button behind the phone my app is miimiza and goes to the background which is the behavior I hope, but when I return to my app does not continue showing my master detail page, but returns to my LginPage.
It is as if my app was running twice or at least there were two instances of LoginPage existing at the same time, this is because in my LoginPage I trigger some DisplayAlert according to some messages that my page is listening through the MessaginCenter and they are they shoot twice.
Can someone tell me how I can return the same to my app on the master detail page and not restart in the strange way described?
LoginView.xaml.cs:
public partial class LogonView : ContentPage
{
LogonViewModel contexto = new LogonViewModel();
public LogonView ()
{
InitializeComponent ();
BindingContext = contexto;
MessagingCenter.Subscribe<LogonViewModel>(this, "ErrorCredentials", async (sender) =>
{
await DisplayAlert("Error", "Email or password is incorrect.", "Ok");
}
);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<LogonViewModel>(this, "ErrorCredentials");
}
}
Part of my ViewModel:
if (Loged)
{
App.token = token;
Application.Current.MainPage = new RootView();
}
else
{
MessagingCenter.Send(this, "ErrorCredentials");
}
Thanks.
I hope this is in Android. All you can do is, you can override the backbuttonpressed method in MainActivity for not closing on back button pressed of the entry page. like below, you can add some conditions as well.
public override void OnBackPressed()
{
Page currentPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.LastOrDefault();
if (currentPage != null)
{
if (currentPage.GetType().Name == "HomePage" || currentPage.GetType().Name == "LoginPage")
{
return;
}
}
base.OnBackPressed();
}
When you press the Home button, the application is paused and the
current state is saved, and finally the application is frozen in
whatever state it is. After this, when you start the app, it is
resumed from the last point it was saved with.
However, when you use the Back button, you keep traversing back in
the activity stack, closing one activity after another. in the end,
when you close the first activity that you opened, your application
exits. This is why whenever you close your application like this, it
gets restarted when you open it again.
Answer taken from this answer. The original question asks about the native Android platform, but it still applies here.
It means you have to Use Setting Plugin or save data in Application properties.
You have to add below code in App.xaml.cs file:
if (SettingClass.UserName == null)
MainPage = new LoginPage();
else
MainPage = new MasterDetailPage();
For Setting Plugin you can refer this link.

Android - Custom back button (back stack)

I have implemented my own back stack but I'm not sure what is wrong or what I could improve, my scenario: I have a project with 2 activities, the first one is the "SplashActivity" - where I load some network data - the second one, the MainActivity.
Inside of my MainActivity I have a fragment and inside of this fragment a webview.
The back button should behave like:
When the user doesn't navigate inside of my webview, close the app.
When the user navigates in webview, use the back history of the browswer.
Here is my code:
#Override
public void onBackPressed() {
Log.d("lastfragment", String.valueOf(fragmentStack.lastElement().getId()));
if (fragmentStack.size() >= 2) {
// implement normal behavior?
Fragment activeFragment=fragmentStack.lastElement();
FragmentTransaction ft = getFragmentManager().beginTransaction();
activeFragment.onPause();
ft.remove(fragmentStack.pop());
Fragment returnToFragment=fragmentStack.lastElement();
String name = returnToFragment.getClass().getName();
if(name=="SplashScreen" || name=="LoginFragment"){
// close?
}
else {
// implement normal behavior?
returnToFragment.onResume();
ft.show(returnToFragment);
ft.commit();
}
}
else {
//close ??
}
}
Try to this code i hope solved this your problem.
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(FragmentTransaction.TRANSIT_FRAGMENT_OPEN, YOUR_FRAGMENT_OBJECT);
fragmentTransaction.addToBackStack(null); // Your fragment add to back stack
fragmentTransaction.commit();

Actionbar up navigation with fragment and activity

I'm going to use home button (Action bar App icon) as back button. I got it to work but not in the way i intended.
My MainActivity is an activity which holds (1) a drawer that shows a list of categories. And a Fragment that displays a list of items in the category chosen in the drawer.
when a item in the list is clicked, a new DetailActivity is started to show the details.
here starts the problem:
From the DetailActivity when i press Back button, it returns to the MainActivity as it was before clicking the item to show details. That is what I expect. However, when use home button as Up navigation, it starts the MainActivity as if I opened the app again. Not showing the list that was previously being shown.
I read in developer documents that for fragments I have to use: .add(detailFragment, "detail") And .addToBackStack() then commit.
But what am I suppose to add in add(---,"---"). And then how should I use it?!
this is my codes:
the method is the MainActivity that shows the content:
public void refreshDisplay(Context context, View view, String category, int i) {
List<Lesson> lessonByCategory = datasource.findByCategory(category, i);
final ListView lv = (ListView) view.findViewById(R.id.listView);
final ArrayAdapter<Lesson> adapter = new LessonListAdapter(context, lessonByCategory);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
Log.i(LOGTAG, "onListItemClick called");
ArrayAdapter<Lesson> m_adapter = adapter;
// get the Lesson object for the clicked row
Lesson lesson = m_adapter.getItem(position);
Intent intent = new Intent(MainActivity.this, LessonDetailActivity.class);
intent.putExtra(".model.Lesson", lesson);
intent.putExtra("isStared", isStared);
startActivityForResult(intent, LESSON_DETAIL_ACTIVITY);
}
});
}
In my LESSON_DETAIL_ACTIVITY that shows the detail content I have this code to enable up navigation for home button:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// I have some other cases here
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
And finally in the Manifest I used the code below to introduce MainActivity as the parrent of LessonDetailActivity:
<activity
android:name=".LessonDetailActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.MainActivity" />
</activity>
I want the Home button as up navigation to behave like back button so that when its clicked it takes me to the MainActivity as it was before opening the LessonDetailActivity. The code above doesn't do that and every time I press Home in the action bar it starts the MainActivity from scratch.
Could anyone help me with this please?
I also should say that I'm new so I'd appreciate it if the answers were detailed.

How can I dismiss listpopupwindow on item selected instead of picking outside the popup

I have android listpopupwindow installed and working in my android app.
I wish to dismiss the popuplist when I click on (and choose) an item instead of clicking outside.
I tried the dismiss(), and dismiss(); break; method anywhere....
I just want to chose an item in the list and after that the popup to go away...
Thanks, Lou
This code worked for me:
popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
popupWindow.dismiss();
}
});

Calling Activity from WebView on shouldOverrideUrlLoading()

In webview, I click a link that takes me to an activity through following code :
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url.equals("factory.cpp")){
Toast.makeText(getApplicationContext(), "Clicked on link", Toast.LENGTH_SHORT).show() ;
Intent intent = new Intent(getApplicationContext(), FactoryCppFiles.class) ;
startActivity(intent) ;
return false ;
}
else
return true ;
}
The FactoryCppFiles activity is displayed properly, but when I press the back button, it shows me the following standard error message.
Web page not available
I want to show the web view where I clicked on the link. How do I achieve this?
Just realized I should return true if I want to handle the URL myself. I switched the return statements and it works fine now.