我在Fragments中有WebView,在一个Fragment中只有一些按钮(不是WebView)。当按下“后退按钮”时,我打算返回WebView的上一页(其余部分,或者当没有上一页时,关闭该应用程序就可以了)。在这里经过几个建议之后,我终于想到了这一点,但是它并没有导致按下返回按钮的上一页。
我不确定是否与Stack Overflow post中的addToBackStack有关;我也不确定如何在我的情况下进行该工作。
public class MyFragment extends Fragment {
public WebView webView;
public boolean WebViewGoBack() {
if(webView.canGoBack()){
webView.goBack();
return true;
}
return false; //webview cannot go back, so use the method of the BackButton
}
}
一个片段是这样实现的:
public class Tab1Fb extends MyFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1fb, container, false);
webView =(WebView)rootView.findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webView.loadUrl("https://www.facebook.com/");
return rootView;
}
}
MainActivity,我有pageradapter和重写的方法:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Fragment mCurrentFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Fb tab1 = new Tab1Fb();
return tab1;
case 1:
Tab2Videos tab2 = new Tab2Videos();
return tab2;
case 2:
Tab3Downloads tab3 = new Tab3Downloads();
return tab3;
case 3:
Tab4Twitter tab4 = new Tab4Twitter();
return tab4;
case 4:
Tab5Contact tab5 = new Tab5Contact();
return tab5;
case 5:
Tab6Support tab6 = new Tab6Support();
return tab6;
default:
return null;
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 6;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FACEBOOK";
case 1:
return "VIDEOS";
case 2:
return "DOWNLOADS";
case 3:
return "TWITTER";
case 4:
return "CONTACT";
case 5:
return "JOIN";
}
return null;
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
@Override
public void setPrimaryItem(View container, int position, Object object) {
if (getCurrentFragment() != object) {
mCurrentFragment = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
}
@Override
public void onBackPressed() {
switch (mViewPager.getCurrentItem()) {
case 0:
if (!webViewGoBack(0)) {
//do something if webview cannot go back
}
break;
case 1:
break;
default:
}
}
public boolean webViewGoBack(int num) {
SectionsPagerAdapter adapter = ((SectionsPagerAdapter)mViewPager.getAdapter());
MyFragment f = (MyFragment )adapter.getCurrentFragment();
if (f!= null) {
return f.WebViewGoBack();
}
return false;
}