So I have this activity that creates 4 fragments for me, which are a bottom navigation bar.
when I change to dark mode or light mode, the fragments reset and take me back to the "main fragment" which is basically home in the bottom navigation bar.
so my question is how do I stay in the tab I was in while changing UI mode? while of course changing the UI mode of the fragments as well
The best aproach is to let activity recreate itself with its fragments, some configuration changes might be required to show correct UI. And its always possible that your user will move your app to the background, system will kill it after a while and then when your user will go back to it - you will be back with your problem of recreation. I am talking about it to prevent you from using hacks like configChanges in androidmanifest which prevent Activity recreation on configuration change event.
But back to the main point:
when configuration change destroys your Activity, fragments will be automatically recreated when new instance of Activity will be created. But its up to you to save some of its state. I am not sure how your UI and code looks like. The very basic way to save and restore state (like active tab in your question) is to use: Activity.onSaveInstanceState(Bundle) / Activity.onCreate(savedInstanceState: Bundle?) and Fragment.onSaveInstanceState(Bundle)/Fragment.onCreate(savedInstanceState: Bundle?) mechanism. You save relevant variables in bundles in onSaveInstanceState, and later in onCreate restore this state using savedInstanceState variable, but only if its non null - which happens when Activity is created for the first time.
This is a broad topic, you can find more on this here:
https://developer.android.com/topic/libraries/architecture/saving-states
https://developer.android.com/guide/fragments/saving-state
Related
I have general questions about BottomNavigationView. I would like to have a BottomNavigationView in each of my Activities in an App for ordering something (e.g. food). It should have 4 buttoms:
Back
Info
Stats
My Orders
With 'Back' the app should just go back to the previous activity. The buttoms 'Stats' and 'My Orders' should switch to a persistent activity that should not be destroyed when not being displayed. 'My Orders' should display the last orders. The buttom 'Info' should only display some information about the current item or current menu (depending from which activity it is called). So basically I have 2 questions:
Should the Activities 'Info', 'Stats', and 'My Orders' be real Activities or just Fragments? Normally I think that at leat 'Stats', and 'My Orders' should be real Activities as they are persistent. But in many BottomNavigationView only Fragments are used?
How can I pass content information to the Activity/Fragment 'Info'. This Activity/Fragment should display information based on the Activity is was called from. Let's say the Activities are different dishes. Do I have to create a separate Info-Activity/Fragment for each dish? Or can I somehow define a dynamic Activity/Fragment that displayes information based on the current Activity?
I'd appreciate every comment and I'd really appreciate your help.
The recommended approach is Single Activity and Multiple fragments.
You can do this using Jetpack's Navigation Component
In case you need to pass data from an Activity/Fragment to the new calling Fragment, it can be done by setting arguments on the calling fragment and then getting it on the called fragment. If there is something which requires to be dynamic, for example- dishes fragment, make a single fragment and common layout and load the data dynamically from the backend.
For Setting Arguments, this should help
How to pass a variable from Activity to Fragment, and pass it back?
Note: You can use fragment without using Navigation Components but you have to use FragmentManager and FragmentTransaction and also have to maintain the Backstack by yourself which could be quite complicated
I have realised an NFC reader application
So i have 3 activities :
MainActivity, which is an activity who contains a Button. If button is clicked, the scan is activated and the user can put his NFC tag against the device to detect it.
WebActivity, who is launched if the NFC tag contains and URL (and open a WebView) or if the user want to launch WebActivity by himself
HistoryActivity, who gonna contains a list of every scans.
Now, I would like to swipe activity with a finger gesture. according to my research on Internet. I need fragments and ViewPager.
But every example that I saw is bases on ONE activity and multiple fragments.
But in my case, I have to create 3 fragments (one per activity), right ?
And I really don't know how to manage my fragment. I mean, what to put inside ?
All I want to do is create a transition/animation while changing activity... That's crazy
This is too broad of a question but hopefully my answer will steer you in right direction.
You should definitely go with single activity/multiple fragments model. Aside of recommendations by Google, you could use navigation components, deep linking much easier then without single activity.
Yes you should be using ViewPager for the purpose (and likely your implementation of FragmentPagerAdapter as well) however I do not understand what kind of swiping will you be doing
Reading your setup, I would suggest to use bottom view with 2 items (good example is here https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample). 2nd one would show history, first one would offer a button that activates your action, and then displays fragment with your WebView.
As a side effect of such implementation, you'd be able to go back from 2nd bottom view item to whatever first one holds - by pressing system back button - which I think is nice touch.
UPDATE to "swiping takes place anytime. " comment:
You could have single activity, ViewPager with 2 fragments. First fragment would display a button, 2nd fragment would display a history. You could freely swipe between them, as you want to. However to me it does not make sense to put WebView screen into this. WebView screen is result of action (NFC detection) and it should probably display as full screen, without any chance of swiping between main/history and itself. Hope it helps or I'm missing some important piece of info you did not share.
The app I'm working on shows some sensitive information that must not be shown on the "Recent Tasks" screen when stopping the app by pressing the home button.
I'd like to blur the sensitive data in the screenshot or show the app logo instead.
I am aware of the following approaches but they don't fit my requirements:
Setting the actvitie's android:excludeFromRecents to true in the manifiest prevents the app from being shown at all in the recent tasks. This would disrupt the user experience.
Using FLAG_SECURE results in a blank card on the recents tasks screen. (How do I prevent Android taking a screenshot when my app goes to the background?) I don't like the blank screen. However, I'll stick to this solution if there is no workaround.
Overriding onCreateThumbnail seems like the ideal solution but, unfortunately, doesn't work as it's currently not invoked by the OS :( (https://code.google.com/p/android/issues/detail?id=29370)
And then there are some workarounds that I tried out but that didn't work as hoped:
Start a new activity that shows the app logo in onPause so that it's screenshot is shown instead of the actual activitie's one. But the new activity takes too long to open and it disrupts the user experience.
Set the activitie's content view to an image of the app logo in onPause. That seemed like a great solution to me. Unfortunately, the screenshot for the recent tasks screen is taken at an unspecified time. During testing the app logo quickly appears before the app is closed when pressing 'Home' but the resulting screenshot shows the activity a short time before that.
Removing the sensitive data from the widgets (e.g. textView.setText("")) has the same problem of screenshot timing just mentioned.
Any alternative ideas or solutions to the listed workarounds?
I looked into this a couple of months ago for the same purpose as you.
Unfortunately, I had to conclude that it is simply not possible. I dug through the android source code and confirmed it.
There is no callbacks or methods from android that allows you to customize it (that works anyway). Besides FLAG_SECURE, this part of the code does not accept any input or change.
OnPause and similar lifecycle methods are called too late (the screenshot is taken already). All lifecycle methods that would hint that you're about to go into the background runs too late.
The image you see in the recent tasks is an actual screenshot - and thus isn't affected by changes you do (too late) to your view. That means you can't modify your view just-in-time (like making it invisible, replacing with something else, adding SECURE_FLAG, or any other obstruction of the view). As an aside, these images can be found on an emulator at /data/system_ce/0/recent_images.
The only exception is using FLAG_SECURE, which will prevent the screenshot from being taken of your application. I experimented with setting this FLAG in onPause and removing it in onResume, however as mentioned already these lifecycle methods runs after the screenshot is taken already, and thus had absolutely no effect.
As discussed in How to change the snapshot shown by recent apps list? there used to be a callback that you could use to customize the thumbnail: onCreateThumbnail. However, this does not work and it is never called. To be clear, the callback is still there, it is simply never called by the OS. The fact that it stopped working is poorly documented, but apparently was silently deprecated/removed in 4.0.3
As for the thumbnail itself, it is a screenshot taken serverside. It is taken before onPause is called (or in fact before any callbacks indicating that your activity is about to go into the background is called).
When your app does go into the background, your actual view is animated (to get that zoom-out transition). That animation can be affected through changes you do in onPause (if you're fast enough that is) (I experimented with setting opacity to 0 on the window among other things). This will however only affect the animation. When the animation is finished, the view is replaced by the screenshot taken earlier.
Also see these questions that discuss this:
When does Android take its recent apps switcher screenshot?
Show custom application image in task manager on ICS or JB
Android never call method onCreateThumbnail
Currently (28/10/2020) is impossibile customizing app thumbnail in recent apps screen.
As explained by #Dellkan in the previous answer, the onCreateThumbnail method is not called anymore by the OS.
Unfortunately, also the suggestion to create a kind of launcher/splash screen without the FLAG_SECURE flag to let the app take a screenshot of that activity is not working, because the screenshot is taken on the activity you see and not at the launch of the app.
You cannot even customize the color of window background when using FLAG_SECURE as reported here.
How about implementing a layout overlay on top of your entire activity?
Make it transparent, it's click-through by default, so no negative impact on UX while in use.
In onPause() set a half-transparent, blurred image as the background of that layout, the data will be scrambled behind it. In onResume() change the background to fully transparent again. Voila.
It might be faster than other types of overlays. The positive side effect is, if you do the unblurring as a short animation effect when the user goes back (with a proper library that uses C++ instead of Java), it might even look cool and the users wouldnt even mind seeing it.
I haven't tried this myself, but it's something you haven't tried yet.
Since onPause is called to late, I use WindowFocusChangeListener to observe when the Fragment loses focus. At this moment we can hide all view which show sensitive data:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.getViewTreeObserver().addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// hide sensitive data when window moves to background (before system screenshot is captured)
myViewWithSensitiveData.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
There is a way to customize it. You need your Activities with sensitive data to FLAG_SECURE in onCreate before you setContentView. Then you need an empty Activity, which renders whatever you want to have as the customized thumbnail. This usually is some sort of splash screen. This new Activity needs to be the launcher and is the only Activity not FLAG_SECURE. This Activity is launched and in onResume starts your actual Activity with the sensitive data.
Android OS will take a screenshot of that new Activity at the beginning of your App. Unfortunately the users will also see this Activity for a short moment. Since every other Activity is FLAG_SECURE, Android OS will use the only available screenshot it made at the beginning.
Was looking for a solution and found some dirty things in case you don't want to use 'FLAG_SECURE'. It doesn't give a nice picture but protects data and doesn't prevent making screenshots for the user while they are in the app.
protected void onPause () {
this.getWindow().getDecorView().getRootView().setScaleX((float)200);
this.getWindow().getDecorView().getRootView().setScaleY((float)200);
super.onPause();
}
protected void onResume () {
this.getWindow().getDecorView().getRootView().setScaleX((float)1);
this.getWindow().getDecorView().getRootView().setScaleY((float)1);
super.onResume();
}
I think this can only achieve through BroadCastReceiver but there is no receiver present. So therefore you first disable default screenshot functionality in android and then implementing your own functionality to take screenshot and before taking screenshot you should blur your secure information.
In a master detail flow, when I go from landscape to portrait, my detail fragment is still there.
What's the best place and time (lifecycle callback) to get rid of it? I only have to get rid of it because my menu items and actionbar title are coming from the detail fragment, in portrait mode, and so it doesn't make any sense.
In the onCreate method of your activity, you could try that:
DetailFragment detailFrag = getFragmentManager().findFragmentByTag
if( <your logic to see if portrait> && detailFrag !=null && detailFrag.isVisible()){
<Remove the Fragment using a normal fragment transaction>
}
Short answer would be onCreate
And there are multiple things you would need to know
When screen orientation change, which is one of the configuration changes, which will trigger Activity recreation.
You can stop Activity recreation by setting onConfigChange, but do NOT do this unless this is a special app, e.g. Camera
Activity recreate is trying to help you, and your case is exactly where it is needed, and you can do the correct setup in onCreate
There are multiple ways to handle the different orientation, the basic way would be to use different layout, e.g. for your layout, say activity_main.xml, you can define a similar xml with the same name, under layout-land folder. When you setContentView(R.layout.activity_main), Android will select the right layout for you depending on your configuration.
In your case, you are switching between 2 fragments and 1 fragment, there are additional works you need to handle for the fragment transaction. However, this would depends on your existing FragmentTransaction and this will go too broad to go on, so I will stop here.
I'm a total beginner with Android and Eclipse and I have few questions that will help me understand the philosophy of Android:
The activity does all the work "behind the scenes". Activities are connected to a layout in the XML file. When the activity is started, if declared in setContentView method, the connected layout will be shown. Activity can be independent, without any layout, it can be invoked by another activity and will do all the work without showing any layout.
Activity is something like a php file which is invoked by my submit button in HTML, and the layout is .HTML which shows elements.
Am I right with this one?
For example, if I want to change the layout of my app, I want to show Layout2.xml when clicking button in Layout1.xml. Then I have to destroy the activity which is connected with Layout1.xml and start the activity which is connected with Layout2.xml? Is this correct? Is there any better way to do this?
How can I (by which method) destroy/stop a certain activity?
Thank you in an advance.
The best bet is to read the Android documentation regarding activites at http://developer.android.com/reference/android/app/Activity.html
I will answer your specific questions here though
An Activity is a window that the user can see (or a hidden window if there is no layout defined). It deals with the logic of a part of the app that the user can see and interact with. If we take the MVC model (Model View Controller), the Activity is the controller, in terms of it controls which data from the Model is shown on the View (the xml layout).
If you want to show a new window/screen/activity you do not need to destroy the current one. You can open a new activity whilst keeping the old one in the background (in the back stack). With the use of fragments, you can have multiple fragments in an activity so rather than changing activities, you can change fragments in a single activity. For more information about fragments take a look at http://developer.android.com/reference/android/app/Fragment.html.
This point relies heavily on the activity lifecycle. When an activity is destroyed, it means it is finishing and this can be done by the user pressing the back button whilst on the activity, the activity calling finish() on itself or by the Android operating system destroying the activity because memory is required elsewhere (this can happen when the app is in the background).
When we say an activity is stopped, it means that the activity is no longer visible to the user. This can be the case where the activity is in the back stack (another activity is in front of it) or if the app has been put into the background.
This is a brief answer to your questions but I highly recommend you read the Android documentation to gain better knowledge.