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.
Related
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
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;
}
}
I am developing an application where i have to display a navigation drawer in home page.I am using NavigationView where i will point which menu it should populate.Now what problem i am facing is, its displaying items twice.Below code will show you what i have done so far
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.view.View;
import android.widget.Toast;
import com.mylaw.rkme3.mylawproject.fragments.HomeFragment;
import com.mylaw.rkme3.mylawproject.fragments.VideoHomeFragment;
import com.mylaw.rkme3.mylawproject.interfaces.FragmentInterface;
import com.mylaw.rkme3.mylawproject.utils.Constants;
/**
* Created by Lincy on 7/4/2016.
**/
public class MainActivity extends AppCompatActivity implements FragmentInterface {
private static final String TAG = "MainActivity";
private Toolbar mToolBar;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
displayScreens();
}
private void initView() {
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mToolBar = (Toolbar) findViewById(R.id.toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setUpNavigationDrawer();
mNavigationView.inflateMenu(R.menu.drawer);
}
private void setUpNavigationDrawer() {
setSupportActionBar(mToolBar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, mToolBar,
R.string.openDrawer,
R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.isChecked())
item.setChecked(false);
else item.setChecked(true);
mDrawerLayout.closeDrawers();
switch (item.getItemId()) {
case R.id.sub_item_in_progress:
goToInProgress();
return true;
case R.id.sub_item_completed:
goToCompleted();
return true;
case R.id.sub_lapsed:
goToLapsed();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
}
private void goToLapsed() {
Intent courseLapsedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Lapsed");
courseLapsedIntent.putExtras(extras);
startActivity(courseLapsedIntent);
}
private void goToCompleted() {
Intent courseCompletedIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "Completed");
courseCompletedIntent.putExtras(extras);
startActivity(courseCompletedIntent);
}
private void goToInProgress() {
Intent courseProgressIntent = new Intent(MainActivity.this, CourseProgressActivity.class);
Bundle extras = new Bundle();
extras.putString(Constants.BundleParameters.FRAGMENT_NAME, "InProgress");
courseProgressIntent.putExtras(extras);
startActivity(courseProgressIntent);
}
private void displayScreens() {
this.action(Constants.FragmentInterfaceConstants.ACTION_HOME, null);
}
#Override
public void action(int tag, Bundle args) {
switch (tag) {
case Constants.FragmentInterfaceConstants.ACTION_HOME:
handleHomeScreen();
break;
case Constants.FragmentInterfaceConstants.ACTION_VIDEO_HOME:
handleVideoHomeScreen();
break;
default:
break;
}
}
#Override
public void showActionBar(boolean show) {
}
#Override
public void showHomeButton(boolean show) {
}
#Override
public void setActionBarTitle(String title) {
}
private void handleHomeScreen() {
HomeFragment homeFragment = new HomeFragment();
addFragment(homeFragment, HomeFragment.TAG);
}
private void handleVideoHomeScreen() {
VideoHomeFragment videoHomeFragment = new VideoHomeFragment();
addFragment(videoHomeFragment, HomeFragment.TAG);
}
private void addFragment(Fragment fragment, String tag) {
FragmentTransaction ft =
getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(tag);
ft.commitAllowingStateLoss();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}else {
getSupportFragmentManager().popBackStack();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_Register:
Intent registerIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle extras = new Bundle();
extras.putString("fragName", "Register");
registerIntent.putExtras(extras);
startActivity(registerIntent);
break;
case R.id.item_search:
Intent searchIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle searchExtras = new Bundle();
searchExtras.putString("fragName", "Search");
searchIntent.putExtras(searchExtras);
startActivity(searchIntent);
break;
case R.id.item_login:
Intent loginIntent = new Intent(MainActivity.this, TransparentActionBarActivity.class);
Bundle loginExtras = new Bundle();
loginExtras.putString("fragName", "Login");
loginIntent.putExtras(loginExtras);
startActivity(loginIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
I have a MainActivity and some fragments and am using WebView to load some site in all the fragments. Before I wasn't able to go to previous page on press of back button but now I am able to. I have everything working but I can't get a fragment to load on startup. If I add this code in the MainActivity to load a fragment automatically, it works but it breaks the back key navigation in other fragments,
getFragmentManager().beginTransaction()
.replace(R.id.content_frame
, new aboutus())
.addToBackStack(null).commit();
Is there any other way by which I can load a fragment by default on startup? Here is my MainActivity (including the code to open fragment automatically) ,
package com.science.s11;
import android.os.Bundle;
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;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.content_frame
, new aboutus())
.addToBackStack(null).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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 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);
}
#Override
public void onBackPressed() {
if (aboutus.mWebView!= null) {
if (aboutus.mWebView.canGoBack()) {
aboutus.mWebView.goBack();
} else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
}else{
finish();}
}
}
else if(amp.mWebView!= null){
if ( amp.mWebView.canGoBack()){
amp.mWebView.goBack();
}else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
}else{
finish();}
}
}
else if(ask.mWebView!= null){
if ( ask.mWebView.canGoBack()){
ask.mWebView.goBack();
}else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
}else{
finish();}
}
}
else if(feedback.mWebView!= null){
if ( feedback.mWebView.canGoBack()){
feedback.mWebView.goBack();
}else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
}else{
finish();}
}
}
else if(subscribe.mWebView!= null){
if ( subscribe.mWebView.canGoBack()){
subscribe.mWebView.goBack();
}else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
}else{
finish();}
}
}
else{
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_aboutus) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new aboutus())
.addToBackStack(null).commit();
// Handle the camera action
} else if (id == R.id.nav_amp) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new amp())
.addToBackStack(null).commit();
} else if (id == R.id.nav_ask) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ask())
.addToBackStack(null).commit();
} else if (id == R.id.nav_feedback) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new feedback())
.addToBackStack(null).commit();
} else if (id == R.id.nav_subscribe) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new subscribe())
.addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is a sample code which I have in all my fragments
package com.science.s11;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.net.NetworkInfo;
public class aboutus extends Fragment {
public static WebView mWebView;
public ProgressBar progressBar;
public LinearLayout layoutProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.aboutus, container, false);
mWebView = (WebView) v.findViewById(R.id.aboutuswebView);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) v.findViewById(R.id.layoutProgress);
mWebView.setVisibility(View.GONE);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings settings = mWebView.getSettings();
settings.setSupportMultipleWindows(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(true);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
super.onPageStarted(view, url, favicon);
}
});
if (isOnline()) {
mWebView.loadUrl("http://science19.com/index.php");
} else {
mWebView.loadUrl("file:///android_asset/cti.html");
}
return v;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return onKeyDown(keyCode, event);
}
public static boolean canGoBack(){
return mWebView.canGoBack();
}
public static void goBack(){
mWebView.goBack();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
}
EDIT (added explanation): I actually want to show a fragment on startup of app, the fragment contains WebView. I can do that using this code,
getFragmentManager().beginTransaction()
.replace(R.id.content_frame
, new aboutus())
.addToBackStack(null).commit();
But I even have other fragments and each and everyone has the ability to go back to previous page on back press. Whenever I use this code, I can't go back to previous page on back press on other fragments, it just works in the fragment which is opened using the code, here it is aboutus. So, why is this actually happening and how can I fix it?
With AppCompatActivity use
getSupportFragmentManager()
instead of
getFragmentManager()
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
}
}