- How to call tab Onclick and OnTabChange for same tab
- 3 Answers 3
- Updating the contents on tab changed in view pager
- 2 Answers 2
- Android how to stop refreshing Fragments on tab change
- 7 Answers 7
- not run oncreate() ,on tab change in same page, 2nd time
- 2 Answers 2
- Implementation guide
- # Opening a Custom Tab
- # Configure the color of the address bar
- # Configure a custom action button
- # Configure a custom menu
- # Configure custom enter and exit animations
- # Warm up the browser to make pages load faster
- # Connect to the Custom Tabs Service
- # Warm up the Browser Process
- # Create a new tab session
- # Tell the browser what URLs the user is likely to open
- # Custom Tabs Connection Callback
- # What happens if the user doesn’t have a browser that supports Custom Tabs installed?
- # How can I check whether the Android device has a browser that supports Custom Tab?
How to call tab Onclick and OnTabChange for same tab
In my project, I have two tabs and a button. For two tabs,I have two activities and button calling different activity. the thing is I am showing result of button on first tab. i.e tab0 is active on tab0Event and on button click event too. And am able to change the tab events using tabHost.setOnTabChangedListener, but now what i further want is, say suppose i click on button so now button view is displaying(tab0 is active) but again if i click on tab0, tab0 activity should be displayed.
I tried many solutions for clicking on tab, one is
But when i used this code with tabChnageListner, tab change not working and i got very unexpected results. Would you please suggest solution for my problem.
code that is working for tab changed is as: (working fine for tab change, need to add Tab Onclick in it)
3 Answers 3
You can implement this listener:
Also when you add tabs set tag for every tab:
You can used Fragment to layout
You cant. Views in TabWidget already have onClickListener and it is required fo normal workflow. If you remove it you will break TabWidget’s logic.
When you set your onClickListener you remove previuos onClickListener and you break TabWidget logic.
Usually in such cases compound click listener is created (a click listener which handles click event and calls another click listener). But not in your case because there is no way to get old click listener because View doesn’t have getOnClickListener method.
This is TabWidget source code. All related values are private. so we can’t fix anithing from this side.
The only way to achieve your goal is a hack with Reflections because they allows to read private vars. So before set View’s new onlick listener you should get old one (using Reflections), then create compound onClickListener which will do your event handling code and then call old onClickListener. Set compound click listener to the View.
Источник
Updating the contents on tab changed in view pager
I am scracthing my head for past 1 day but unable to find the solution. In mine application there are two tabs under the toolbar
- First tab is USER-TAB
- the second one is ADMIN-TAB
In both the tabs there are the listView. When a ListItem on the USER-TAB is clicked a dialog appears and user take some action.
Now after this when the ADMIN-TAB is Selected the Admin should get refreshed with new sets of data. But It’s not. On selecting the ADMIN-TAB the onResume() method and everyting is getting called but it is not able to update the list.
I wont be able to write the Whole code, I am giving some snippet. Basically I have taken the code from this link
https://github.com/codepath/android_guides/wiki/Sliding-Tabs-with-PagerSlidingTabStrip
In My Main Activity I have written the OpPageChangeListener.
OnPageSelected You can see I am detaching and reattaching the fragment.Everything is working fine. Both Fragments OnResume() are getting called but the List is not getting changed. I don’t undrstand why
For additional assistance i am adding snippet one Fragment. Hope this will give some Idea where i might be going wrong
2 Answers 2
Haah.. Finally i got an answer to after an heck of losing almost 1 and half days. It might be not completely good answer but atleast it is one of the closest I got.
First of all MainActivity.java looks like:
Now what I have done here is I have set OnPageChangeListener and in this I am keeping track of the position whenever the tabs are changing. For my needs what i have done is i have created two boolean variables and setting it when any content on those tab are changing in Application scope. Now when the contents on one tab has been changed or some Action are done I am calling
viewPagerAdapter.notifyDataSetChanged() // Now this is the real gem
after invoking this it will make a call to the ViewPagerAdapter function
Also the Point is your ViewPagerAdapter should extend FragmentStatePageAdapter. Now the Point is
will not cache the fragment and reload a new fragment for that tab position. Basic idea is we should not make or retutn PagerAdapter.POSITION_NONE everytime on sliding of tab since it destroys the cached element and reload the fragment which affects UI performance.
So finally the basic thing is always check that whether on calling viewPagerAdapter.notifyDataSetChanged() the function getItemPosition() should also gets invoked. Hope it will help somebody. For better perfomance you can make changes according to your requirement.
I got the needed breakthrough and understanding from this post : @Louth Answer
Remove Fragment Page from ViewPager in Android
Источник
Android how to stop refreshing Fragments on tab change
I have the following code :
MainActivity.java
TabsPagerAdapter.java
I’m making a library application in which the navigation is by tabs, the problem is each time I go from the third tab to the first or the first to the third, the tab content is refreshing, I want to prevent the refresh, Any help please ?
7 Answers 7
By default, ViewPager recreates the fragments when you swipe the page. To prevent this, you can try one of three things:
1. In the onCreate() of your fragments, call setRetainInstance(true) .
2. If the number of fragments is fixed & relatively small, then in your onCreate() add the following code:
3. Use a FragmentPagerAdapter as part of your ViewPager .
If I remember correctly, the second option is more promising. But I urge you to try all three and see which of them work.
one has to instance the FragmentPagerAdapter first, then .getCount() will return a value —
while .getCount() — 1 should be set as the default off-screen limit:
you can handle view recreation by check if the view is null or not
In the onCreate() of your fragments, call setRetainInstance(true)
A bit late to this question, but thanks to Y.S., got to know how ViewPager works. I was building an app with 4 tabs and at any point of time, noticed that only two tabs were being refreshed, which I suppose was a default behaviour. After hours of investigation, I understood that Android refreshes multiple tabs to bring in a smooth swiping performance for the user — you might notice that you would have clicked tab2, but android brings in the data for tab3 and keeps it ready.
Though this behaviour is good, it has its pros and cons. Pros — you get a smooth swiping experience, without data being loaded from an external server when you land up in that tab. Cons-your backstack implementation in tabs could go for a toss. When you click a tab, the view pager actually calls smoother tab and you’ll end up in a big trouble, if your methods are setting up backarrow (home) at the top left based on what is in the backstack in the clicked tab.
setOffscreenPageLimit is the answer to this. If you want your custom backstack framework to function, and do not want tab3 to be called when tab2 is clicked, you simply need to set the value to the number of tabs. For instance, if you have 4 tabs, set setOffScreePageLimit(4). This would mean that Android would refresh all the 4 fragments initially, which is a bit of a performance overhead (which you should manage properly). But, your backstack and tab switching remain intact. Hope this helps.
Источник
not run oncreate() ,on tab change in same page, 2nd time
I have 4 tabs in a page view when i click first time on tab it executes it oncreate() method of corresponding tab and when i go to other tab on same page and again click on previous clicked tab then its oncreate() method not execute why?why it is not work as button click means each time i click its oncreate() method run.
my code for tab activity class is below
then can i go to other activity means using
we can load again activity on tab click??then what to written in place of
2 Answers 2
Tabs that contain activities are implemented by means of ActivityGroup. When someone changes a tab, corresponding activity is created only if necessary. When you move to any tab for the second time, the activity is already existing and only its window is shown. You should use instead:
TabActivity with separate activities as a content are a little bit tricky so maybe you should consider using Views instead. If not you can use the following code to access all activities from each other:
get instances of content activities from TabActivity:
where name is given in newTabSpec() method.
get instance of TabActivity from content activities:
Using these method you can create communication between all activities (using proper casting). For example:
If you want to change activities under tabs you should use:
Источник
Implementation guide
Published on Tuesday, February 4, 2020 • Updated on Tuesday, December 8, 2020
A complete example is available on the GitHub sample application. It contains re-usable classes to customize the UI, connect to the background service, and handle the lifecycle of both the application and the custom tab activity.
If you follow the guidance from this page, you will be able to create a great integration.
The first step for a Custom Tabs integration is adding the AndroidX Browser Library to your project. Open the app/build.gradle file and add the browser library to the dependencies section.
Once the Browser Library is added to your project there are two sets of possible customizations:
- Customizing the UI and interaction with the custom tabs.
- Making the page load faster, and keeping the application alive.
The UI Customizations are done by using the CustomTabsIntent and the CustomTabsIntent.Builder classes; the performance improvements are achieved by using the CustomTabsClient to connect to the Custom Tabs service, warm-up the browser and let it know which urls will be opened.
# Opening a Custom Tab
A CustomTabsIntent.Builder can be used to configure a Custom Tab. Once ready, call CustomTabsIntent.Builder.build to create a CustomTabsIntent and launch the desired Url with CustomTabsIntent.launchUrl .
# Configure the color of the address bar
One of the most important (and simplest to implement) aspects of Custom Tabs is the ability for you to change the color of the address bar to be consistent with your app’s theme.
The snippet below changes the background color for the address bar. colorInt is an int that specifies a Color .
# Configure a custom action button
As the developer of your app, you have full control over the Action Button that is presented to your users inside the browser tab.
In most cases, this will be a primary action such as Share, or another common activity that your users will perform.
The Action Button is represented as a Bundle with an icon of the action button and a PendingIntent that will be called by the browser when your user hits the action button. The icon is currenlty 24dp in height and 24-48 dp in width.
- icon is a Bitmap to be used as the image source for the action button.
- description is a String be used as an accessible description for the button.
- pendingIntent is a PendingIntent to launch when the action button or menu item was tapped. The browser will be calling PendingIntent#send on taps after adding the url as data. The client app can call Intent#getDataString to get the url.
- tint is a boolean that defines if the Action Button should be tinted.
# Configure a custom menu
The browser has a comprehensive menu of actions that users will perform frequently inside a browser, however they may not be relevant to your application context.
Custom Tabs will have a set of default actions provided by the browser. Those actions can include items like «Forward», «Page Info», «Refresh», «Find in Page» or «Open in Browser».
As the developer, you can add and customize up to five menu items that will appear between the icon row and foot items.
A menu item is added by calling CustomTabsIntent.Builder#addMenuItem with title and a PendingIntent that browser will call on your behalf when the user taps the item are passed as parameters.
# Configure custom enter and exit animations
Many Android applications use custom View Entrance and Exit animations when transitioning between Activities on Android. Custom Tabs is no different, you can change the entrance and exit (when the user presses Back) animations to keep them consistent with the rest of your application.
# Warm up the browser to make pages load faster
By default, when CustomTabsIntent#launchUrl is called, it will spin up the browser and launch the URL. This can take up precious time and impact on the perception of smoothness.
We believe that users demand a near instantaneous experience, so we have provided a Service that your app can connect to and tell the browser and its native components to warm up. Custom Tabs also provide the ability for you, the developer to tell the browser the likely set of web pages the user will visit. Browsers will then be able to perform:
- DNS pre-resolution of the main domain
- DNS pre-resolution of the most likely sub-resources
- Pre-connection to the destination including HTTPS/TLS negotiation.
The process for warming up the browser is as follows:
- Use CustomTabsClient#bindCustomTabsService to connect to the service.
- Once the service is connected, call CustomTabsClient#warmup to start the browser behind the scenes.
- Call CustomTabsClient#newSession to create a new session. This session is used for all requests to the API.
- Optionally, attach a CustomTabsCallback as a parameter when creating a new session, so that you know a page was loaded.
- Tell the browser which pages the user is likely to load with CustomTabsSession#mayLaunchUrl
- Call the CustomTabsIntent.Builder constructor passing the created CustomTabsSession as a parameter.
# Connect to the Custom Tabs Service
The CustomTabsClient#bindCustomTabsService method takes away the complexity of connecting to the Custom Tabs service.
Create a class that extends CustomTabsServiceConnection and use onCustomTabsServiceConnected to get an instance of the CustomTabsClient . This instance will be needed on the next steps.
# Warm up the Browser Process
Warms up the browser process and loads the native libraries. Warmup is asynchronous, the return value indicates whether the request has been accepted. Multiple successful calls will also return true.
Returns true if successful.
# Create a new tab session
Session is used in subsequent calls to link mayLaunchUrl call, the CustomTabsIntent and the tab generated to each other. The callback provided here is associated with the created session. Any updates for the created session (see Custom Tabs Callback below) is also received through this callback. Returns whether a session was created successfully. Multiple calls with the same CustomTabsCallback or a null value will return false.
# Tell the browser what URLs the user is likely to open
This CustomTabsSession method tells the browser of a likely future navigation to a URL. The method warmup() should be called first as a best practice. The most likely URL has to be specified first. Optionally, a list of other likely URLs can be provided. They are treated as less likely than the first one, and have to be sorted in decreasing priority order. These additional URLs may be ignored. All previous calls to this method will be deprioritized. Returns whether the operation completed successfully.
# Custom Tabs Connection Callback
Will be called when a navigation event happens in the custom tab. The navigationEvent int is one of 6 values that defines the state of the page is in. See below for more information.
# What happens if the user doesn’t have a browser that supports Custom Tabs installed?
Custom Tabs is supported by most Android browsers. Nevertheless, since it uses an ACTION_VIEW Intent with key Extras to customize the UI it will open in the system browser, or the user’s default browser if Custom Tabs is not supported.
If the user has a browser that supports Custom Tab installed and it is the default browser, it will automatically pick up the EXTRAS and present a customized UI.
# How can I check whether the Android device has a browser that supports Custom Tab?
It is possible to use the PackageManager to query the Android device for applications that can handle Custom Tabs. We query for applications that are able to handle http Intents, then check if those applications also declare support for the Custom Tabs Service:
Android 11 has introduced package visiblity changes. If your Android app is targeting API level 30 or above, adding a queries section to AndroidManifest.xml is needed, otherwise the code snippet above won’t return results:
Last updated: Tuesday, December 8, 2020 Improve article
Источник