2013-09-10 3 views
0

Я создаю приложение с вкладками, используя webview на всех вкладках. Каждая вкладка переходит на другой URL-адрес, где пользователь может затем щелкнуть ссылки, и он покажет им ссылку в приложении. Однако у меня возникла проблема с внедрением кнопки «Назад», чтобы пользователь мог вернуться к предыдущей странице. Вот мой MainActivity.java:Back button force close app

package com.theprospectordaily; 

import java.util.Locale; 

import android.app.ActionBar; 
import android.app.FragmentTransaction; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 
import android.support.v4.view.ViewPager; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.view.KeyEvent; 
import android.content.Intent; 


public class MainActivity extends FragmentActivity implements 
ActionBar.TabListener { 


    WebView myWebView; 
    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     // Check if the key event was the Back button and if there's history 
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
      myWebView.goBack(); 
      return true; 
     } 
     // If it wasn't the Back key or there's no web page history, bubble up to the default 
     // system behavior (probably exit the activity) 
     return super.onKeyDown(keyCode, event); 
    } 

/** 
* The {@link android.support.v4.view.PagerAdapter} that will provide 
* fragments for each of the three primary sections of the app. We use a 
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which 
* will keep every loaded fragment in memory. If this becomes too memory 
* intensive, it may be best to switch to a 
* {@link android.support.v4.app.FragmentStatePagerAdapter}. 
*/ 
CollectionPagerAdapter mCollectionPagerAdapter; 

/** 
* The {@link android.support.v4.view.ViewPager} that will display the 
* object collection. 
*/ 
ViewPager mViewPager; 

public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 




// Create an adapter that when requested, will return a fragment 
// representing an object in 
// the collection. 
// 
// ViewPager and its adapters use support library fragments, so we must 
// use 
// getSupportFragmentManager. 
mCollectionPagerAdapter = new CollectionPagerAdapter(
    getSupportFragmentManager()); 

// Set up action bar. 
final ActionBar actionBar = getActionBar(); 


// Specify that we will be displaying tabs in the action bar. 
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

// Set up the ViewPager, attaching the adapter and setting up a listener 
// for when the 
// user swipes between sections. 
mViewPager = (ViewPager) findViewById(R.id.pager); 
mViewPager.setAdapter(mCollectionPagerAdapter); 
mViewPager 
    .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 
     @Override 
     public void onPageSelected(int position) { 
     // When swiping between different app sections, select 
     // the corresponding tab. 
     // We can also use ActionBar.Tab#select() to do this if 
     // we have a reference to the 
     // Tab. 
     actionBar.setSelectedNavigationItem(position); 
     } 
    }); 

// For each of the sections in the app, add a tab to the action bar. 
for (int i = 0; i < mCollectionPagerAdapter.getCount(); i++) { 
    // Create a tab with text corresponding to the page title defined by 
    // the adapter. 
    // Also specify this Activity object, which implements the 
    // TabListener interface, as the 
    // listener for when this tab is selected. 
    actionBar.addTab(actionBar.newTab() 
     .setText(mCollectionPagerAdapter.getPageTitle(i)) 
     .setTabListener(this)); 
} 
} 

public void onTabUnselected(ActionBar.Tab tab, 
    FragmentTransaction fragmentTransaction) { 
} 

public void onTabSelected(ActionBar.Tab tab, 
    FragmentTransaction fragmentTransaction) { 
// When the given tab is selected, switch to the corresponding page in 
// the ViewPager. 
mViewPager.setCurrentItem(tab.getPosition()); 
} 

public void onTabReselected(ActionBar.Tab tab, 
    FragmentTransaction fragmentTransaction) { 
} 


/** 
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to 
* one of the primary sections of the app. 
*/ 
public class CollectionPagerAdapter extends FragmentPagerAdapter { 

final int NUM_ITEMS = 5; // number of tabs 

public CollectionPagerAdapter(FragmentManager fm) { 
    super(fm); 
} 

@Override 
public Fragment getItem(int i) { 
    Fragment fragment = new TabFragment(); 
    Bundle args = new Bundle(); 
    args.putInt(TabFragment.ARG_OBJECT, i); 
    fragment.setArguments(args); 
    return fragment; 
} 

@Override 
public int getCount() { 
    return NUM_ITEMS; 
} 

@Override 
public CharSequence getPageTitle(int position) { 
    String tabLabel = null; 
    switch (position) { 
    case 0: 
    tabLabel = getString(R.string.label1); 
    break; 
    case 1: 
    tabLabel = getString(R.string.label2); 
    break; 
    case 2: 
    tabLabel = getString(R.string.label3); 
    break; 
    case 3: 
    tabLabel = getString(R.string.label4); 
    break; 
    case 4: 
    tabLabel = getString(R.string.label5); 
    } 

    return tabLabel; 
} 
} 

/** 
* A fragment that launches other parts of the demo application. 
*/ 
public static class TabFragment extends Fragment { 

public static final String ARG_OBJECT = "object"; 

private WebView webView; 
private Bundle webViewBundle; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    webViewBundle = new Bundle(); 
} 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) { 

    Bundle args = getArguments(); 
    int position = args.getInt(ARG_OBJECT); 

    int tabLayout = 0; 
    switch (position) { 
    case 0: 
    tabLayout = R.layout.tab1; 
    break; 
    case 1: 
    tabLayout = R.layout.tab2; 
    break; 
    case 2: 
    tabLayout = R.layout.tab3; 
    break; 
    case 3: 
    tabLayout = R.layout.tab4; 
    break; 
    case 4: 
     tabLayout = R.layout.tab5; 
    break; 
    } 

    View rootView = inflater.inflate(tabLayout, container, false); 

    webView = (WebView) rootView.findViewById(R.id.webView1); 
    if (webView != null) { 
    webView.setWebViewClient(new WebViewClient()); 

    if (webViewBundle == null || webViewBundle.isEmpty()) { 
     webView.loadUrl("http://www.theprospectordaily.com/category/news/"); 
    } else { 
     webView.restoreState(webViewBundle); 
     webViewBundle.clear(); 

    } 
    } 

    webView = (WebView) rootView.findViewById(R.id.webView2); 
    if (webView != null) { 
    webView.setWebViewClient(new WebViewClient()); 


    if (webViewBundle == null || webViewBundle.isEmpty()) { 
     webView.loadUrl("http://www.theprospectordaily.com/category/entertainment/"); 
    } else { 
     webView.restoreState(webViewBundle); 
     webViewBundle.clear(); 
    } 
    } 

    webView = (WebView) rootView.findViewById(R.id.webView3); 
    if (webView != null) { 
    webView.setWebViewClient(new WebViewClient()); 

    if (webViewBundle == null || webViewBundle.isEmpty()) { 
     webView.loadUrl("http://www.theprospectordaily.com/category/sports/"); 
    } else { 
     webView.restoreState(webViewBundle); 
     webViewBundle.clear(); 
    } 
    } 

    webView = (WebView) rootView.findViewById(R.id.webView4); 
    if (webView != null) { 
    webView.setWebViewClient(new WebViewClient()); 

    if (webViewBundle == null || webViewBundle.isEmpty()) { 
     webView.loadUrl("http://www.theprospectordaily.com/category/multimedia/"); 
    } else { 
     webView.restoreState(webViewBundle); 
     webViewBundle.clear(); 
    } 
    } 

    webView = (WebView) rootView.findViewById(R.id.webView5); 
    if (webView != null) { 
    webView.setWebViewClient(new WebViewClient()); 

    if (webViewBundle == null || webViewBundle.isEmpty()) { 
     webView.loadUrl("http://www.theprospectordaily.com/category/perspectives/"); 
    } else { 
     webView.restoreState(webViewBundle); 
     webViewBundle.clear(); 
    } 
    } 



    return rootView; 
} 
} 

} 

Это мой первый раз узнать, как код, так что я понимаю, что это повсюду, и это, вероятно, имеет много ошибок. Я заранее извиняюсь за это!

+0

, пожалуйста, разместите здесь ошибку logcat. – dipali

ответ

1

Где вы начинаете команду myWebView? Я не уверен, что вы пытаетесь сделать, но из своего кода я уверен, что myWebView имеет значение null, когда вы вызываете myWebView.canGoBack(), он выкинет NullPointerException.

+0

Хмм, я не уверен, что вы просите. Можете ли вы привести пример инициализации myWebView, а затем я могу найти его в своем коде? – user2763406

+0

@ user2763406 Вы не знаете, что означает инициализация переменной? Это базовое программирование, и я не понимаю, как вы написали столько кода, не зная, что делаете. Что такое ссылка myWebView? Прямо сейчас вы сказали, что myWebView является WebView, но не дал ему значения. Далее в вашем коде вы добавили другие веб-просмотры, например: webView = (WebView) rootView.findViewById (R.id.webView2);) Итак, где myWebView иналинизируется? – nedaRM

0

Почему вы перекрывая onKeyDown

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     // Check if the key event was the Back button and if there's history 
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { 
      myWebView.goBack(); 
      return true; 
     } 
     // If it wasn't the Back key or there's no web page history, bubble up to the default 
     // system behavior (probably exit the activity) 
     return super.onKeyDown(keyCode, event); 
    } 

Вы можете сделать это он должен это специфический метод

@Override 
public void onBackPressed() 
{  
     if (myWebView.canGoBack()) { 
      myWebView.goBack(); 
      return true; 
     } 
    super.onBackPressed();  

} 

Примечание: Но я предлагаю реализовать свою собственную кнопку назад для WebView, так что пользователь можете использовать кнопку возврата для существующих из деятельности

0

Попробуйте переопределить onBackPressed в вашем ctivity.

@Override 
public void onBackPressed() { 
    if (mWebView.canGoBack()) { 
    mWebView.goBack(); 
    } else { 
    super.onBackPressed(); 
    } 
} 
0

Что вам нужно сделать, это переопределить функцию onBackPressed. Это позволит вам делать все, что вам нужно, когда нажата кнопка «Назад».

@Override 
public void onBackPressed() { 
    wv.goBack(); 

    //uncomment this if you want the back button to behave as normal 
    //super.onBackPressed(); 
}