I am trying to exit a web view called on the click of a fragment's element.
Here's my code:
public class MainActivity extends AppCompatActivity {
private WebView webView;
private CustomPagerAdapter customPagerAdapter;
private ViewPager2 viewPager;
TabLayout tabLayout;
static MainActivity activity;
static MainActivity activity;
public static MainActivity getInstance(){
return activity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
setContentView(R.layout.main_activity);
viewPager = (ViewPager2) findViewById(R.id.pager_main);
tabLayout = (TabLayout) findViewById(R.id.tab_layout_main);
setPagerAdapter();
customPagerAdapter.addFragment(new GoogleFragment());
customPagerAdapter.addFragment(new YouTubeFragment());
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> {
if (position == 0) {
tab.setText("Google");
} else if (position == 1) {
tab.setText("YouTube");
}
}
).attach();
}
private void setPagerAdapter(){
customPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), getLifecycle());
viewPager.setAdapter(customPagerAdapter);
}
public void setWebView(String url) {
setContentView(R.layout.web_view);
webView = (WebView) getInstance().findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return false;
}
});
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
finish();
}
}
}
On pressing back button, instead of exiting the web view, the app exits itself. The webView.goBack() works fine. But clicking back button from the main url, exits the app.
Any help is appreciated!
Related
I'm using Fragments to change scenes in my application, and I've come across the problem where when the phone back button is pressed, the application closes. How would I make it so when the back button is pressed, the previous fragment opens.
I searched for solutions and there are quite a few like using getChildFragmentManager or back stack. I just don't know how to implement it for my specific state pager adapter, of which I followed a youtube video tutorial for.
SectionsStatePagerAdapter.java:
public class SectionsStatePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
public SectionsStatePagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public SectionsStatePagerAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
public SectionsStatePagerAdapter mSectionsStatePagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Fragment Stuff:
mSectionsStatePagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
mViewPager = findViewById(R.id.container);
//SetUpPager:
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager){
SectionsStatePagerAdapter adapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
adapter.addFragment(new MainPageFragment(),"MainPage"); //0
adapter.addFragment(new CoffeePageFragment(),"CoffeePage"); //1
adapter.addFragment(new RegularCoffeeFragment(),"RegularCoffeePage"); //2
viewPager.setAdapter(adapter);
}
public void setViewPager(int fragmentNumber){
mViewPager.setCurrentItem(fragmentNumber);
}
}
CoffeePageFragment.java:
public class CoffeePageFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_coffee_page,container,false);
btnRegularCoffee = view.findViewById(R.id.regular_coffee_button);
btnRegularCoffee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setViewPager(2);
}
});
return (view);
}
}
In conclusion, how do I make it so when the device back button is pressed, it will go back to the previous fragment?
In previous versions of the AppCompatActivity implementation it was enough to override onBackPressed() in your activity, newer versions dictate to implement the OnBackPressedCallback, like shown here: https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher.html
public class FormEntryFragment extends Fragment {
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(
true // default to enabled
) {
#Override
public void handleOnBackPressed() {
showAreYouSureDialog();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(
this, // LifecycleOwner
callback);
}
}
It might still be ok to use onBackPressed on the Activity level, though.
I got a problem with updating ViewPager fragments. We need to show fragments with data to registered user, when he doesn't registered we need to show fragments with message to register. I use this method to check it in MainActivity:
#Override
public void setAdapter(boolean isUserExist) {
Log.d("RegDebug", "In setAdapter");
mainPagerAdapter.clearData();
mainPagerAdapter.addFragment(searchFragment, getString(R.string.search_title));
if (isUserExist) {
Log.d("RegDebug", "In setAdapter reg");
mainPagerAdapter.addFragment(new ChatsFragment(), getString(R.string.chats_title));
mainPagerAdapter.addFragment(new ActionsFragment(), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Registered!", Toast.LENGTH_SHORT).show();
} else {
Log.d("RegDebug", "In setAdapter unreg");
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.CHATS_TAB_NAME), getString(R.string.chats_title));
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.ACTIONS_TAB_NAME), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Unregistered!!!", Toast.LENGTH_SHORT).show();
}
mainPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(mainPagerAdapter);
}
I call this method in presenter with setting value from firebase auth, checking if user exists:
public void checkForUserExist() {
if (mainInteractor.isUserExist()) {
getViewState().setRegAdapter();
} else getViewState().setUnregAdapter();
}
And then call presenter method in onCreate of MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialogFragment = new FilterDialogFragment();
searchFragment = new SearchFragment();
//UI
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.main_view_pager);
tabLayout = findViewById(R.id.main_tabs);
//mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
mainPresenter.checkForUserExist();
tabLayout.setupWithViewPager(viewPager);
}
I try to log the boolean result and it returns exactly value that must be, but pager adapter can't update its content.Code of MainPagerAdapter:
public class MainPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentTitleList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
public void clearData(){
fragmentList.clear();
fragmentTitleList.clear();
notifyDataSetChanged();
Log.d("RegDebug", " fragmentList size is " + fragmentList.size()
+ " fragmentTitleList size is " + fragmentTitleList.size());
}
}
Use OnPageChangeListener of ViewPager class & notify to your current fragment from there using interface.
I have an activity who load a list of data, this activity its a TabActivity with 3 Tabs, all tabs load a diferent data type.
But the data may be really a bunch of data, for that reason my activity may take a lot of time to show itself.
I start teh activity using
Intent intent = new Intent(MainActivity.this, PcapAnalisys.class);
startActivity(intent);
Then, when the activity is loading shows a black screen, and after a few seconds show the content properly.
There is a way on how to show a message like: "Loading activity... please wait" or something?
This is my code for a my TabActivity:
public class PcapAnalysis extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pcap_analysis);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setImageResource(R.drawable.ic_attach_file_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FileChooserDialog dialog = new FileChooserDialog(PcapAnalysis.this);
dialog.show();
dialog.addListener(new FileChooserDialog.OnFileSelectedListener() {
#Override
public void onFileSelected(Dialog source, File file) {
source.hide();
Toast.makeText(source.getContext(),
"File selected: " + file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
Log.i("Archivo seleccionado", file.getAbsolutePath());
new AsyncTask_load(PcapAnalysis.this, file.getAbsolutePath()).execute();
}
public void onFileSelected(Dialog source, File folder, String name) {
source.hide();
Toast.makeText(source.getContext(),
"File created: " + folder.getName() + "/" + name,
Toast.LENGTH_LONG).show();
}
});
}
});
new Task().execute();
}
#Override
public void recreate()
{
super.recreate();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pcap_analysis, 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);
}
/*public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pcap_analysis, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}*/
private class Task extends AsyncTask<Void, Integer, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(PcapAnalysis.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Procesando...");
pDialog.setCancelable(true);
pDialog.setMax(100);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager.setOffscreenPageLimit(3); //cuantas paginas se precargan
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
//publishProgress(progress);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Fragment http = new HttpList();
private Fragment dns = new DnsList();
private Fragment ip = new IpList();
private Fragment resume = new ResumeList();
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return http;
case 1:
return dns;
case 2:
return ip;
case 3:
return resume;
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "HTTP";
case 1:
return "DNS";
case 2:
return "RESOURCE IP";
case 3:
return "RESUME";
}
return null;
}
}
}
As you can see this activity use fragments to show the data, and each fragment has a for cicle to load the data (that is in a String array).
Also I use a AsyncTask trying to solve this problem, but is not working. Please help!
Im trying to figure out how to determine what fragment is shown. I unfourantly cannot figure out how to start going about writing this code. Here is my source below.
Fragment
public class Fragment1 extends SherlockFragment {
WebView web;
static ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inf, ViewGroup grp, Bundle icicle) {
View v = inf.inflate(R.layout.activity_main, grp, false);
web = (WebView) v.findViewById(R.id.webView);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
setHasOptionsMenu(true);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
web.setWebViewClient(new SpecialWebView(progressBar));
web.setWebChromeClient(new SpecialWebChromeClient(progressBar));
// Progress Bar - End
WebSettings websettings = web.getSettings();
websettings.setBuiltInZoomControls(false);
web.setBackgroundColor(Color.parseColor("#f2f2f2"));
websettings.setUseWideViewPort(true);
websettings.setJavaScriptEnabled(true);
websettings.setAllowFileAccess(true);
websettings.setDomStorageEnabled(true);
websettings.setLoadWithOverviewMode(true);
websettings.setSavePassword(true);
web.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater Inflater = getSupportMenuInflater();
Inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
final int current = ((ViewPager) mFragments).getCurrentItem();
String currentId = current == 0 ? FRAGMENT1: (current == 1 ? FRAGMENT2: FRAGMENT3);
//WebView web = (WebView) findViewById(currentId);
switch (Item.getItemId()) {
case R.id.menu_back:
web.goBack();
return true;
case R.id.menu_forward:
web.goForward();
return true;
case R.id.menu_refresh:
web.reload();
return true;
}
return super.onOptionsItemSelected(Item);
}
MainActivity
public class MainActivity extends SherlockFragmentActivity {
private ViewPager mPager;
private TitlePageIndicator mIndicator;
private MainPagerAdapter mAdapter;
private List<Fragment> mFragments;
private static final String FRAGMENT1 = Fragment1.class.getName();
private static final String FRAGMENT2 = Fragment2.class.getName();
private static final String FRAGMENT3 = SupportFragment.class.getName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_main);
// add fragments
mFragments = new ArrayList<Fragment>();
mFragments.add(Fragment.instantiate(this, FRAGMENT1));
mFragments.add(Fragment.instantiate(this, FRAGMENT2));
mFragments.add(Fragment.instantiate(this, FRAGMENT3));
// adapter
mAdapter = new MainPagerAdapter(getSupportFragmentManager(), mFragments);
// pager
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setOffscreenPageLimit(3);
mPager.setAdapter(mAdapter);
// indicator
mIndicator = (TitlePageIndicator) findViewById(R.id.title_indicator);
mIndicator.setViewPager(mPager);
}
I'm not sure what adapter you're subclassing, but why not override the getView() callback to set a class variable for your activity? Then you could just check the value of the variable every time you want know which fragment is showing.
#Override
public Fragment getItem(int position) {
MainActivity.setCurrentlyShownFragment(position);
return SomeFragment.newInstance(position);
}
That's the easiest way that I'm aware of.
Figuring out whether a Fragment is shown isn't that hard. In your Fragment code just override setUserVisibleHint(). This takes a boolean that is true if the fragment UI is visible and false if it is not.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Do something
} else {
//Do something else
}
}
You then just include what you want to do in the visible case and non-visible case within the appropriate parts of the conditional statment. Depending on what you're trying to do this may involve using an Interface to pass data to the containing fragment activity so you can reach other fragments or perform certain activity based functions.
I'm currently using FragmentStatePagerAdapter and I would like it to have a "navigate up" feature (DisplayHomeAsUpEnabled). When I set the following code it shows up as a correct navigate back button. But nothing happens when I click on it, can you guys see anything that I', doing wrong in my code, I get no error while pressing the "navigate up" button and I get no compiler errors.
Here is the code, its in the "public boolean onOptionsItemSelected(MenuItem item) {" it gets interesting at the bottom.
public class ShareholdingDetailFragment extends FragmentActivity {
final int NUM_ITEMS = Portfolio.getPortfolio().count();
MyAdapter mAdapter;
ViewPager mPager;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(NUM_ITEMS + "e");
super.onCreate(savedInstanceState);
setContentView(R.layout.shareholdingdetailview_fragment_wrapper);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
public int getCount() {
return NUM_ITEMS;
}
public Fragment getItem(int position) {
return ShareholdingFragment.newInstance(position);
}
}
public static class ShareholdingFragment extends Fragment {
int mNum;
static ShareholdingFragment newInstance(int num) {
ShareholdingFragment f = new ShareholdingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#SuppressLint({ "NewApi", "NewApi" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shareholdingdetailview_fragment, container, false);
/****************Setting the Display as home and it shows*******************/
ActionBar bar = getActivity().getActionBar();
bar.setDisplayHomeAsUpEnabled(true);
/**********************************/
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home://Not working
System.out.println("test");//This isn't printed out
Intent upIntent = new Intent(getActivity(), DetailShareHoldingActivity.class);
if (NavUtils.shouldUpRecreateTask(getActivity(), upIntent)) {
getActivity().finish();
} else {
NavUtils.navigateUpTo(getActivity(), upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Try adding: setHasOptionsMenu(true); in your onCreate() in ShareholdingFragment.
Add setHomeButtonEnabled(true) on API Level 14 and higher when you configure your action bar. On API Level 11-13, the home button is enabled automatically.
If you're using the new Toolbar and ActionbarDrawerToggle. You can assign clickHandler directly. For my activities that have this drawer toolbar I implemented an interface to enable drawer if at root,
#Override
public void enableDrawer(boolean enable) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Pop fragment back stack or pass in a custom click handler from the fragment.
}
});
}