Progress bar is not working in MainActivity - android

i am not able to implement progress bar in main activity it is showing cannot resolve the method 'findViewById'
and i want to why it showing like that because so many time i got stuck in this problem, i am a beginner so i am asking hope you developer bro's help me.
here is the code of MainActivity
package com.fb.jaisonjoseph.facebookbasic;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.view.KeyEvent;
/**
* A simple {#link Fragment} subclass.
*/
public class Home_Fragment extends Fragment {
public ProgressBar bar;
public WebView mwebView;
public Home_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
WebView view=(WebView) rootView.findViewById(R.id.webView);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
//bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
return rootView;
}
private class MyWebViewClient extends WebViewClient {
ProgressBar bar=(ProgressBar)findViewById(R.id.progressBar);
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
here is screenshot of MainActivity
code for activity
package com.fb.jaisonjoseph.facebookbasic;
import android.app.FragmentManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.security.PrivateKey;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
WebView view=(WebView) rootView.findViewById(R.id.webView);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
return rootView;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Home_Fragment home_fragment=new Home_Fragment();
android.support.v4.app.FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relative_layour_fragment, home_fragment,home_fragment.getTag()).commit();
} else if (id == R.id.nav_profile) {
Profile_Fragment profile_fragment=new Profile_Fragment();
android.support.v4.app.FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relative_layour_fragment,profile_fragment,profile_fragment.getTag()).commit();
} else if (id == R.id.nav_messages) {
} else if (id == R.id.nav_notifications) {
} else if (id == R.id.nav_chat) {
} else if (id == R.id.nav_chat) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

You have to declare progress bar global and declare in OncreateView like this.
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.view.KeyEvent;
/**
* A simple {#link Fragment} subclass.
*/
public class Home_Fragment extends Fragment {
public ProgressBar bar;
public WebView mwebView;
ProgressBar bar;
public Home_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
//bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
return rootView;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
Check my code Hope this helps.:)

ProgressBar bar;//declare as global
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_, null);
WebView view=(WebView) rootView.findViewById(R.id.webView);
bar=(ProgressBar) rootView.findViewById(R.id.progressBar);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
return rootView;
}

Have a look at this solution
public class Home_Fragment extends Fragment {
public ProgressBar bar;
public WebView mwebView;
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_home_, null);
bar=(ProgressBar)rootView.findViewById(R.id.progressBar);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
return rootView;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}

method findViewById does not belong to the class MyWebViewClient where you are trying to access it.
to fix this problem, you need to keep the reference or ProgressBar in the fragment and then access it from MyWebViewClient.
change your code to:
package com.fb.jaisonjoseph.facebookbasic;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
/**
* A simple {#link Fragment} subclass.
*/
public class Home_Fragment extends Fragment {
public ProgressBar bar;
public WebView mwebView;
public Home_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home_, null);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.loadUrl("https://mbasic.facebook.com");
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyWebViewClient());
bar=(ProgressBar)rootView.findViewById(R.id.progressBar); //uncomment this
return rootView;
}
private class MyWebViewClient extends WebViewClient {
// ProgressBar bar=(ProgressBar)findViewById(R.id.progressBar); Not needed
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(final WebView view, final String url, final Bitmap favicon) {
bar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
}
EDIT
Also update your activity code to:
package com.fb.jaisonjoseph.facebookbasic;
import android.app.FragmentManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.security.PrivateKey;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Home_Fragment home_fragment=new Home_Fragment();
android.support.v4.app.FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relative_layour_fragment, home_fragment,home_fragment.getTag()).commit();
} else if (id == R.id.nav_profile) {
Profile_Fragment profile_fragment=new Profile_Fragment();
android.support.v4.app.FragmentManager manager=getSupportFragmentManager();
manager.beginTransaction().replace(R.id.relative_layour_fragment,profile_fragment,profile_fragment.getTag()).commit();
} else if (id == R.id.nav_messages) {
} else if (id == R.id.nav_notifications) {
} else if (id == R.id.nav_chat) {
} else if (id == R.id.nav_chat) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Related

Android Studio toolbar title updating error with back stack from one fragment to the another fragment

i have a fragment_home that has 6 buttons and these 6 buttons have there own link(to display something like registration form ) but i have one button from these 6 buttons which is linked to another fragment and has tabbed view with view pager the title of any other fragment will update when i press back but when i entered to the button that links to the tabbed view it makes the toolbar title constant and it won't update there the application unless i exit and open again
for more information i have added some photos with description below
shortly
when application Starts
first image
when i clicked users
second image
when i click back
third image
it updates the title correctly , when i click register own
fourth image
it updates correctly again but now when i press back
last image
it doesnt update the title
main navigation class
package com.example.arada_tech.myapplication;
import android.nfc.Tag;
import android.support.v4.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class Navi extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment1;
DrawerLayout drawer;
Tag tag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navi);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Displayfragment(R.id.nav_home);
}
boolean doubleBackToExitPressedOnce=false;
// #Override
// public void onBackPressed() {
//
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// if (drawer.isDrawerOpen(GravityCompat.START)) {
// drawer.closeDrawer(GravityCompat.START);
//
// } else {
// if (getFragmentManager().getBackStackEntryCount() > 1) {
// getFragmentManager().popBackStack();
// } else if (!doubleBackToExitPressedOnce) {
// this.doubleBackToExitPressedOnce = true;
// Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();
// new Handler().postDelayed(new Runnable() {
// #Override
// public void run() {
// doubleBackToExitPressedOnce = false;
// }
// }, 2000);
// }
// else {
// System.exit(1);
//// 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.navi, 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);
}
private void Displayfragment(int id)
{
Fragment fragment=null;
switch(id) {
case R.id.nav_home:
fragment = new Fragment_Home();
break;
case R.id.nav_addbirr:
// fragment = new Fragment_addbirr();
break;
case R.id.nav_adduser:
fragment = new Fragment_addusers();
break;
case R.id.nav_followorders:
// fragment = new Fragment_followorders();
break;
case R.id.nav_Deleteusers:
// fragment = new Fragment_deleteusers();
break;
case R.id.nav_setings:
// fragment = new Fragment_settings();
Intent tin=new Intent(getApplicationContext(),Menus.class);
startActivity(tin);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
fragment1=fragmentManager.findFragmentById(R.id.nav_home);
ft.replace(R.id.myframelayout,fragment);
// ft.addToBackStack(fragment.getClass().getName());
ft.addToBackStack(fragment.getClass().getName());
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Displayfragment(item.getItemId());
return true;
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
my Fragment_home
package com.example.arada_tech.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class Fragment_Home extends Fragment implements View.OnClickListener {
CardView im,in,du,ro;
Fragment fragment=null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("home");
return inflater.inflate(R.layout.mukera,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
im= (CardView) view.findViewById(R.id.card_user);
ro= (CardView) view.findViewById(R.id.card_registerown);
im.setOnClickListener(this);
ro.setOnClickListener(this);
in= (CardView) view.findViewById(R.id.card_order);
in.setOnClickListener(this);
du= (CardView) view.findViewById(R.id.card_deleteuser);
du.setOnClickListener(this);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onClick(View v) {
if(v==im){
fragment = new Fragment_addusers();
FragManager();
}
else if (v==in)
{
// fragment = new Fragment_followorders();
FragManager();
}
else if (v==du)
{
// fragment = new Fragment_deleteusers();
FragManager();
}
else if (v==ro)
{
fragment = new Fragment_registerown();
FragManager();
}
}
public void FragManager()
{
if(fragment!=null)
{
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction ft= fragmentManager.beginTransaction();
ft.replace(R.id.myframelayout,fragment);
ft.addToBackStack(null);
ft.commit();
}
}
}
and my registerown fragment
package com.example.arada_tech.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_registerown extends Fragment {
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("register Own");
setHasOptionsMenu(true);
return inflater.inflate(R.layout.mainslide,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("View"));
tabLayout.addTab(tabLayout.newTab().setText("Create"));
tabLayout.addTab(tabLayout.newTab().setText("Edit"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
final ViewAdapter adapter = new ViewAdapter(((FragmentActivity) getContext()).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) {
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// super.onViewCreated(view, savedInstanceState);
}
for any help thanks in advance
you just need to debug and check
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
method is call or not on the back event of register own fragment.you are not mentions the code line where you called setActionBarTitle() method in the code.
It works when i delete the first two lines of code in registerown_fragment in onviewcreated method Thank you for your help

issues with onBackpressed and ProgressDialog in android fragment for webview

In my android app i have created 4 tabs with the fragment and each tab loads different URL, which works fine but,
1) how do i add onBackpressed to each webview to load previous page on back click? I know how to do it in java class but Override doesn't work in Fragment.
2) my second question is I have added a ProgressDialog to each webview which works fine but covers whole layout until full webpage is loaded, how do i make it show only on top like browsers, while able to view and scroll loaded webpage?
Following is my code for fragment.
GoogleFragment.java
Public class GoogleFragment extends Fragment {
WebView myWebView;
ProgressDialog pd;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_webview, container, false);
final ProgressDialog pd = ProgressDialog.show(getContext(), "", "Loading Please wait...", true);
myWebView = (WebView) v.findViewById(R.id.WebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com/");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
String webUrl = myWebView.getUrl();
}
});
return v;
}
}
MainActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.nav.R;
import com.nav.fragments.TabFragment;
import java.util.Timer;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private InterstitialAd interstitial;
public Timer AdTimer;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer) ;
int width = getResources().getDisplayMetrics().widthPixels/2;
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationView.getLayoutParams();
params.width = width;
mNavigationView.setLayoutParams(params);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_home) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
}
if (menuItem.getItemId() == R.id.drawer_facebook){
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_gPlus){
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_more) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_profile) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_share) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_youtube) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_exit) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#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 void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
} }
TabFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
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 com.nav.R;
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 6 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_layout, container, false);
tabLayout = (TabLayout) v.findViewById(R.id.tabs);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new GoogleFragment();
case 1 : return new SportsFragment();
case 2 : return new GamesFragment();
case 3 : return new PhotographyFragment();
case 4 : return new WildFragment();
case 5 : return new TravelFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return getResources().getString(R.string.tab1);
case 1 :
return getResources().getString(R.string.tab2);
case 2 :
return getResources().getString(R.string.tab3);
case 3 :
return getResources().getString(R.string.tab4);
case 4 :
return getResources().getString(R.string.tab5);
case 5 :
return getResources().getString(R.string.tab6);
}
return null;
}
}
}
You can change onBackPressed in the activity:
http://pastebin.com/3DR4nDWM
And in your fragment class:
public boolean goBack()
{
if(webView.canGoBack())
{
webView.goBack();
return true;
}
return false;
}
Try adding ProgressBar on top of the WebView.

Android app webview opens in browser instead of the app

package com.slimolobeapp.slimolobe;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.net.URL;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initilizing webview
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
mywebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("http://www.slimolobeapp.com");
//force links open in webview
mywebView.setWebViewClient(new MyWebClient());
}
#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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_shop) {
mywebView.loadUrl("http://www.slimolobeapp.com/shop");
} else if (id == R.id.nav_category) {
mywebView.loadUrl("http://www.slimolobeapp.com/category");
} else if (id == R.id.nav_price) {
mywebView.loadUrl("http://www.slimolobeapp.com/price");
} else if (id == R.id.nav_contact) {
mywebView.loadUrl("http://www.slimolobeapp.com/contact");
} else if (id == R.id.nav_facebook) {
mywebView.loadUrl("http://www.facebook.com/slimolobe");
} else if (id == R.id.nav_instagram) {
mywebView.loadUrl("http://www.instagram.com/slimolobe");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.slimolobeapp.com")) {
//open url content in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
//goto previous page when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mywebView.canGoBack()) {
mywebView.goBack();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
return false;
}
}
Here is my main activity code, I don't know where I am doing it wrong. Every time I open the app, the web view launches a browser, the apps did not load the web page, it only loads in the browser and I don't want this.
I believe you need to set your WebView client before you call loadUrl().
try this code
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://www.google.com");
setContentView(mWebview );
}
}

Can't Go Back in Webviews

Hello i have a small problem with my project. I have a sliding menu with webviews . But i can't go back in webviews, when i push the button to go back my app just crash. I tryed with OnBackPressed method and OnKeyDown, but no one of this work. here is my code. just the main activity class and webviewfragment class
Where shoul i put the methods to work fine ? In webview fragment class, not work because webviews extend fragment, no fragmentActivity.
package com.pavan.slidingmenu;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
WebView webview ;
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
// #Override
// public void onBackPressed()
// {
// if(webview.canGoBack())
// webview.goBack();
// else
// super.onBackPressed();
// }
// #Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if(event.getAction() == KeyEvent.ACTION_DOWN){
// switch(keyCode)
// {
// case KeyEvent.KEYCODE_BACK:
// if(webview.canGoBack()){
// webview.goBack();
// }else{
// finish();
// }
// return true;
// }
//
// }
// return super.onKeyDown(keyCode, event);
// }
}
package com.pavan.slidingmenu;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setBuiltInZoomControls(true);
settings.setPluginState(PluginState.ON);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new 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);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
You just need to make your WebViewFragment implement an Interface, like this:
public interface onBackPressedInterface
{
public void onBackPressedWebView();
}
The only method of the Interface will be implemented on your fragment, so you have to add implements clause on your Fragment declaration, like this:
public class MyWebViewFragment extends Fragment implements onBackPressedInterface{
and implement the method like this:
/**
* the user presses the back button
*/
#Override
public void onBackPressedWebView()
{
if (webview.canGoBack()){
webview.goBack();
((MainActivity) getActivity()).canGoBack=true;
}
else{
((MainActivity) getActivity()).canGoBack=false;
getActivity().onBackPressed();
}
}
In your MainActivity, add a boolean variable that defines if you make the normal back behaviour or execute the Interface method on your Fragment. It is public so the Fragment can access it and modify it when there is no more backs to make on the WebView. It is true at the begginig so the interface method could be allways called at the first time the user clicks back button.
public boolean canGoBack = true;
Once the user clicks the back button, the onBackPressed() callback is called on your MainActivity, so overrite it like this:
#Override
public void onBackPressed()
{
if(canGoBack)
((onBackPressedInterface)getSupportFragmentManager().findFragmentById(R.id.webview_fragment)).onBackPressedWebView();
if(!canGoBack)
super.onBackPressed();
}
R.id.webview_fragment is the id of the fragment that I have declared in my Activity layout file.
So, when the user clicks back button, the fragment method is called, it checks if the webview can go back. If it can, goes back and keeps the Activity boolean true so it can be executed again when a new click occurs.
When the WebView has no more backs, the variable is set to false and the normal onBackPressed method is executed, by calling getActivity().onBackPressed().
This is what your Activity layout should be like, with one fixed Fragment component:
<?xml version="1.0" encoding="utf-8"?>
<fragment
android:id="#+id/webview_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.pavan.slidingmenu.MyWebViewFragment" />
If you do not want to have a fixed Fragment in your layout, just create a call in your MyWebViewFragment to create an instance of your fragment, like:
MyWebViewFragment.newInstance() and call the interface callback on that Fragment

Android - ActionBarSherlock Navigation Drawer and Fragments with Activities

I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}

Categories

Resources