Menu Button on ViewPager toasts wrong position - android

I am loading local htmls in webview using Viewpager. This works fine and the right page is loaded from the WebViewFragment into viewpager activity. Scroll or swipe works fine, but I added a menu button to get the title of the current webview, and to toast it. This menu button returns the webview title of the next 2 webview pages in the viewpager.
Reducing the setOfScreenLimit to 1 toasts the webview title of the next webview page in the viewpager. I cant setOfScreenLimit to 0. What is the most probable way to get the current item's webview title when the menu button is clicked. I need to get this and save to a DB.
Code:
ViewPager
ViewPager pager = (ViewPager) findViewById(R.id.pager);
TabsPagerAdapterEnglish pageAdapter = new TabsPagerAdapterEnglish(getSupportFragmentManager());
Bundle extras = getIntent().getExtras();
int value = 0;
if (extras != null) {
value = extras.getInt("keyHTML");
}
pager.setAdapter(pageAdapter);
pager.setCurrentItem(value);
pager.setOffscreenPageLimit(1);
Adapter
public class TabsPagerAdapterEnglish extends FragmentPagerAdapter {
private static int NUM_ITEMS = 3
public TabsPagerAdapterEnglish(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
#Override
public int getCount() {
return NUM_ITEMS;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WebFragmentEnglish.newInstance(0, "file:///android_asset/page1.html");
case 1:
return WebFragmentEnglish.newInstance(1, "file:///android_asset/page2.html");
case 2:
return WebFragmentEnglish.newInstance(2, "file:///android_asset/page3.html");
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
}
}
WebFragment
public class WebFragmentEnglish extends Fragment {
// newInstance constructor for creating fragment with arguments
public static WebFragmentEnglish newInstance(int position, String url) {
WebFragmentEnglish fragmentFirst = new WebFragmentEnglish();
Bundle args = new Bundle();
args.putInt("page_position", position);
args.putString("keyHTML", url);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
if (null != toolbar) {
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
}
position = getArguments().getInt("page_position", 0);
url = getArguments().getString("keyHTML");
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().finish();
case R.id.action_addtofav:
webView = (WebView) getActivity().findViewById(R.id.webView1);
htitle = webView.getTitle();
saveData();
Toast.makeText(getActivity(), htitle + " added to favorite",
Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
// Inflate the view for the fragment based on layout XML
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
webView = (WebView) view.findViewById(R.id.webView1);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return true;
}
});
webView.setLongClickable(false);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
webView.loadUrl(url);
return view;
}

ViewPager will load the current page and the next page(s) up to the offScreenLimit. To get the name of the current page you need to get the current position of the adapter.
It's hard to give more specific help without having code posted. But you can use the ViewPager getCurrentItem method to get the visible index. From there you can either compare it to the index of the page you're displaying (this works if the view pager is static and pages are known in advance), or you can use that index to get the Fragment from the PagerAdapter and call a method on it to save the name.

I was able to solve the problem with the ViewPager.
I removed the toolbar instance from the fragment to use the one in the viewpager's activity. Then in my options menu, you would notice I used
webView = (WebView) **getActivity().**findViewById(R.id.webView1);
I removed the this completely, since i have already defined it in the onCreateView, I think maybe its because of the getActivity field I added to locate the webview ID.
I was updating an old code, I'm glad I was able to solve this. Thank you #Chisko and #Ben

Related

Progress bar loading before I select the Tab

Here is my code for Tab Initialization:
private void initTabs() {
serviceTabs.addTab(serviceTabs.newTab().setText("Request Appointment"));
serviceTabs.addTab(serviceTabs.newTab().setText("Online Booking"));
serviceTabs.addTab(serviceTabs.newTab().setText("Feedback"));
serviceViewpager.setOffscreenPageLimit(serviceTabs.getTabCount());
final ViewPageAdapter adapter = new ViewPageAdapter(getChildFragmentManager(), serviceTabs.getTabCount(),
mContext);
serviceViewpager.setAdapter(adapter);
serviceViewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(serviceTabs));
serviceTabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
serviceViewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
Log.i("", "on tab unselected Service");
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Log.i("", "on tab reselected Service ");
}
});
}
private class ViewPageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
Context context;
ViewPageAdapter(FragmentManager fm, int numOfTabs, Context context) {
super(fm);
this.mNumOfTabs = numOfTabs;
this.context = context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CustomizeFragment();
case 1:
Bundle url = new Bundle(); url.putString(Constants.WEB_URL,Constants.APPOINTMENT_ONLINE_BOOKING);
return WebViewFragment.createInstance(url);
case 2:
return new CustomizeFragment();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
And I'm having the progress bar loading inside the WebViewFragment as Follows:
public static WebViewFragment createInstance(Bundle urlArgs) {
WebViewFragment webView = new WebViewFragment();
webView.setArguments(urlArgs);
return webView;
}
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle saveInstanceState) {
rootView = layoutInflater.inflate(R.layout.load_web_view, container, false);
activity = getActivity();
url=getArguments().getString(Constants.WEB_URL);
mContext = activity.getApplicationContext();
serviceAppointmentView = (WebView) rootView.findViewById(R.id.webView);
loadData();
return rootView;
}
public void loadData()
{
serviceAppointmentView.clearView();
webSettings = serviceAppointmentView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
progress = new Progress(activity);
pDialog = progress.showProgress();
pDialog.setCanceledOnTouchOutside(true);
serviceAppointmentView.loadUrl(url);
serviceAppointmentView.setWebViewClient(new
DealerWebViewClient());
}
private class DealerWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progress.dismissProgress(pDialog);
}
}
Im Using the custom progress bar for Online Booking Tab. The problem here is the Progress begins to load before I tap the Online Booking tab. Please tell me where i'm doing the mistake or how could be this solved...Thanks for patiently looking on my code and any suggestions will be helpful for me...!
ViewPage has DEFAULT_OFFSCREEN_PAGES value which is 1, and it is the min value, you can not set it to 0.
It means that when you are initing the viewpager and the fragments are added, when it does init fragment at postion 0 it does also init fragment at position 1.
There is a method, inside Fragment.class
setUserVisibleHint(boolean)
which is called when the fragment is visible to user(getting selected in viewPager).
You can ovveride it to achieve your loading progress start whenever you need.
Keep inmind that it is also fired before
onCreateView()
You can check if view is already inflated checking if any view is not null.
View pager will by default load atleast 1 on the right and one on the left tab of current tab. It is done so, mostly because there is a point when u slide viewpager, when certain area of both tabs is visible. For those smooth transitions preloading is required.
To prevent this you can use this method setUserVisibleHint().
Like below code:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
}
}
I hope it will help you.
As viewpager loads adjacent fragments of current fragment , Its better to use progressbar in xml like this following while working with the viewpager inseted of progressdialog or something :
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:visibility="visible" />
By default Viewpager can load the three pages at a time.one is the current page and remaining are left and right side of the current page.So if you open your activity opposite sides of your fragments will also intializes.so overrride this method in your fragment below your onCreate()
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
loaddata();
}else{
}
}
This will call whenever your fragment is visible to user

Go back in webview by pressing "back button"

How can I go back one page while in webview? For example: I am on my app in activity and browsing pages in webview, but once I press back button it will exit the app or just goes back in activity instead of the page..
I have done my research and overriding onBackPressed function doesnt work.
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
Whole fragment code:
public class FragmentTwo extends Fragment {
public FragmentTwo() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment2, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
WebView webView = (WebView) getActivity().findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.setScrollbarFadingEnabled(false);
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://myapp.com");
}
}
Any suggestions of how to achieve it?
onBackPressed() is method of Activity, not of a Fragment, so this code will never be invoked. If you want to do something on back press, your parent activity must let your fragment know about it - you must implement onBackPressed() in parent activity and in that method you should call fragments' method (or fire event on event bus, or use listeners, callback, whatever).
Also right method name is onCreateView(), not onViewCreated() - this one won't be called either.
Inside of the your OnCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_layout, container, false);
webView = (WebView) view.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(expertsUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Ok! In your MainActivity you will write it:
#Override
public void onBackPressed() {
if(yourname_Fragment.webView!=null){
if (yourname_Fragment.webView.canGoBack()) {
yourname_Fragment.webView.goBack();
}
}
}
yourname_Fragmen.java= This is your nameFragment that content the Webview
webView= The name of your WebView (id)
Now. Inside of your Fragment you have to declare static global variable
public static Webview webView;
NOTE: If you have more than one fragment you have to check if this instance is different of NULL;
And that's it! Good luck!

Logic to use multiple webview in TabLayout to handle memory issue

I have almost 30 webview in a Tablayout. Everything works fine but my app consumes a lot of memory and will just close because of memory issue. This is what I get in log
04-05 21:00:09.458 19720-19801/com.example.choman.webview A/chromium: [FATAL:memory.cc(19)] Out of memory. size=16777216
This is my java file. Basically all the remaining 29 fragments contain the same code with just a change in the url. I am not sure how to handle this.
public class stackOverflow extends Fragment {
private WebView webView;
private ProgressBar progressBar1;
private SwipeRefreshLayout mSwipeRefreshLayout1;
public stackOverflow() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
progressBar1 = (ProgressBar) view.findViewById(R.id.progressBar1);
webView = (WebView) view.findViewById(R.id.website_detail_1);
webView.setWebViewClient(new MyAppWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://www.stackoverflow.com");
WebSettings webSettings = webView.getSettings();
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
mSwipeRefreshLayout1 = (SwipeRefreshLayout) view.findViewById(R.id.swipe1);
mSwipeRefreshLayout1.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.loadUrl("http://www.stackoverflow.com");
}
});
if (mSwipeRefreshLayout1.isRefreshing()) {
mSwipeRefreshLayout1.setRefreshing(false);
}
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
}
public class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.findViewById(R.id.progressBar1).setVisibility(View.GONE);
Log.i("pageFinished", "yesss");
//progressBar.setVisibility(View.INVISIBLE);
progressBar1.setVisibility(View.GONE);
if (mSwipeRefreshLayout1.isRefreshing()) {
mSwipeRefreshLayout1.setRefreshing(false);
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Mainactivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public WebView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("WebView1").setTag("WebView1"));
//all the way down to .....
tabLayout.addTab(tabLayout.newTab().setText("WebView30").setTag("WebView30"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(6);
final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout
.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(
tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.WebView1) {
viewPager.setCurrentItem(0);
//all the way down to..30
if (id == R.id.WebView30) {
viewPager.setCurrentItem(30);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the code for TabPagerAdapter
public class TabPagerAdapter extends FragmentStatePagerAdapter
{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs)
{
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
//
WebViewFragment1 tab1 = new WebViewFragment1();
return tab1;
//all the way to tab 29
webViewFragment30 tab30 = new WebViewFragment30();
return tab30
default:
return null;
}
}
#Override
public int getCount()
{
return tabCount;
}
}
Use ViewPager. ViewPager will hold maximum 3 fragments in memory at any time(without changing the default offscreen page limit). The 3 fragments are the current visible fragment, left and right side fragments to the current fragment.
If you want tabs, you could create a custom View which looks like the system Tabs and add it above the ViewPager. Use PageTransformer with ViewPager to track the ViewPager swipe and scroll the custom Tab accordingly. Then listen to the clicks of Tabs and scroll the ViewPager based on the Tab pressed.
Update:
I totally forgot that we could attach a TabLayout with a ViewPager instead of creating custom Tabs.
tabLayout.setUpWithViewPager(viewpager) will work.
Thanks to #choman
viewPager.setOffscreenPageLimit(6); This line is causing the issue. This line tells the view pager to keep (6+6+1 = 13) pages in memory which should be costly in your case since each page has 6.5 Mb of contents. You need to change it to viewPager.setOffscreenPageLimit(1) to fix the OutOfMemory issue.
Quoting your comment, "I am using only single webview in app but my webpage having 6.5MB size. So it was main reason of app crash".
If your webpage is 6.5MB size, my hunch is that it is because of some large size high quality images. If that is the case, you should consider reducing the size of the images by downscaling/ downsampling the images. Downscaling the images at the server side is much better than doing that in mobile after downloading(waste of bandwidth, CPU, battery).
You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.
it causes because your application need more space to run.
i think it will help you to solve out current problem.
--how to use--
<application
....
android:largeHeap="true" >
thanks
WebView is heavy component.
I would recommend to change your application to work with single webview and changing url in it instead of multiple webview usage.

WebView with FragmentStatePagerAdapter goes blank on calling setCurrentItem

I am working on Swipe Views with Tabs. The code provided in the "EffectiveNavigation" project at the Creating Swipe Views with Tabs page provides a solid starting ground. Experimenting further I added an OnClickListener to the given TextView and added a setCurrentItem to the onClick method. This behaves as expected and the ViewPager jumps to the requested page.
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
((TextView) rootView.findViewById(android.R.id.text1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*
*setCurrentPagerItem(5); -> omitted here to reduce complexity
*/
mViewPager.setCurrentItem(5);
}
});
return rootView;
}
}
As the project I'm working on requires the loading of static webpages instead of text. I replaced the TextView with a WebView to load a different webpage at every swipe. This works perfectly well. Click events from the HTML side are handled by a JavascriptInterface I have implemented.
It is here that I'm facing a problem. The setCurrentPagerItem method works perfectly well when called outside of the JavascriptInterface. When called from within the JavascriptInterface the WebView shows a blank screen and stays so until a swipe to the right or left is made. A swipe to the right displays the next page to the one requested and a swipe to the left displays the requested page. LogCat shows no errors and this behaviour is consistent across a 4.3 based emulator and a Nexus 7 running 4.4.4. I shall provide the entire code below.
public class CollectionDemoActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments representing
* each object in a collection. We use a {#link android.support.v4.app.FragmentStatePagerAdapter}
* derivative, which will destroy and re-create fragments as needed, saving and restoring their
* state in the process. This is important to conserve memory and is a best practice when
* allowing navigation between objects in a potentially large collection.
*/
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the object collection.
*/
ViewPager mViewPager;
private static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
context = this;
// Create an adapter that when requested, will return a fragment representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must use
// getSupportFragmentManager.
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
final OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int pos) {
final Toast pageNo;
pageNo = Toast.makeText(context,"PAGE "+(Integer.toString(pos+1))+"/100",Toast.LENGTH_SHORT);
pageNo.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
pageNo.cancel();
}
}, 100);
}
};
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
mViewPager.setOnPageChangeListener(mPageChangeListener);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void setCurrentPagerItem(int item) {
mViewPager.setCurrentItem(item);
}
/**
* A {#link android.support.v4.app.FragmentStatePagerAdapter} that returns a fragment
* representing an object in the collection.
*/
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
final WebView webView = (WebView) rootView.findViewById(R.id.webView);
switch(args.getInt(ARG_OBJECT)) {
case 1 :
webView.loadUrl("file:///android_asset/html/index.html");
break;
default :
webView.loadUrl("file:///android_asset/html/page_"+(Integer.toString(args.getInt(ARG_OBJECT)-1))+".html");
break;
}
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Object()
{
#JavascriptInterface
public void toPage(String pageNo) {
((CollectionDemoActivity) getActivity()).setCurrentPagerItem(4);
}
}, "external");
return rootView;
}
}
}
I could be wrong but it sounds like you are not updating on the UIThread.
You could try something like this.
getActivity().runOnUiThread(new Runnable(){
#Override
public void run() {
((CollectionDemoActivity) getActivity()).setCurrentPagerItem(4);
}
});

How to integrate shouldOverrideUrlLoading in my Activity

I have 6 tabs and 6 webviews i want to add this
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
}else if(url.startsWith("http:") || url.startsWith("https:")) {
view.loadUrl(url);
}
return true;
}
only for tab 6 in my MainActivity.java to handle the tel: links how can i make it work with my code ?
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the three primary sections of the app. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
CollectionPagerAdapter mCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the
* object collection.
*/
ViewPager mViewPager;
WebView myWebView;
WebView tab1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an adapter that when requested, will return a fragment
// representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must
// use
// getSupportFragmentManager.
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is
// no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener
// for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(6);
mViewPager.setAdapter(mCollectionPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select
// the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if
// we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mCollectionPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onBackPressed(){
// Rezolvarea butonului back
WebView webViewa = (WebView) findViewById(R.id.webView1);
WebView webViewb = (WebView) findViewById(R.id.webView2);
WebView webViewc = (WebView) findViewById(R.id.webView3);
WebView webViewd = (WebView) findViewById(R.id.webView4);
if ( webViewa.canGoBack()) {
webViewa.goBack();
}
if ( webViewb.canGoBack()) {
webViewb.goBack();
}
if ( webViewc.canGoBack()) {
webViewc.goBack();
}
if ( webViewd.canGoBack()) {
webViewd.goBack();
}
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the primary sections of the app.
*/
public class CollectionPagerAdapter extends FragmentPagerAdapter {
final int NUM_ITEMS = 6; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new TabFragment();
Bundle args = new Bundle();
args.putInt(TabFragment.ARG_OBJECT, i);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
String tabLabel = null;
switch (position) {
case 0:
tabLabel = getString(R.string.label1);
break;
case 1:
tabLabel = getString(R.string.label2);
break;
case 2:
tabLabel = getString(R.string.label3);
break;
case 3:
tabLabel = getString(R.string.label4);
break;
case 5:
tabLabel = getString(R.string.label6);
break;
case 4:
tabLabel = getString(R.string.label5);
break;
}
return tabLabel;
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class TabFragment extends Fragment {
public static final String ARG_OBJECT = "object";
private WebView webView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position) {
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
case 3:
tabLayout = R.layout.tab4;
break;
case 5:
tabLayout = R.layout.tab6;
break;
case 4:
tabLayout = R.layout.tab5;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
webView = (WebView) rootView.findViewById(R.id.webView1);
WebView tab2 = (WebView) rootView.findViewById(R.id.webView2);
WebView tab3 = (WebView) rootView.findViewById(R.id.webView3);
WebView tab4 = (WebView) rootView.findViewById(R.id.webView4);
WebView tab5 = (WebView) rootView.findViewById(R.id.webView5);
WebView tab6 = (WebView) rootView.findViewById(R.id.webView6);
if (webView != null) {
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/tab1.html");
}
if (tab2 != null) {
tab2.setWebViewClient(new WebViewClient());
tab2.loadUrl("file:///android_asset/tab2.html");
}
if (tab3 != null) {
tab3.setWebViewClient(new WebViewClient());
tab3.loadUrl("file:///android_asset/tab3.html");
}
if (tab4 != null) {
tab4.setWebViewClient(new WebViewClient());
tab4.loadUrl("file:///android_asset/tab4.html");
}
if (tab5 != null) {
tab5.setWebViewClient(new WebViewClient());
WebSettings tb5 = tab5.getSettings();
tb5.setJavaScriptEnabled(true);
tab5.loadUrl("http://fbhostinger.com/po/map.html");
}
if (tab6 != null) {
tab6.setWebViewClient(new WebViewClient());
tab6.loadUrl("file:///android_asset/tab5.html");
}
return rootView;
}
}
}
also my tab6 loads a html file from assets with this
if (tab6 != null) {
tab6.setWebViewClient(new WebViewClient());
tab6.loadUrl("file:///android_asset/tab5.html");
}
I think you just need to do:
if (tab6 != null) {
tab6.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
return false;
}
return true;
}
});
tab6.loadUrl("file:///android_asset/tab5.html");
}
Please note the adaption of no longer calling view.loadUrl('...'); <- if you return true in shouldOverrideURLLoading, it will load the url into the WebView.

Categories

Resources