2013-03-25 5 views
0

Я - относительно новый разработчик Android и в настоящее время заканчиваю свое первое приложение для Android.Android: onBackPressed() для просмотра веб-страниц в фрагменте

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

1) Я хочу, чтобы пользователь мог использовать кнопку назад на устройстве, чтобы вернуться в веб-просмотра

2) Я пытаюсь передать GPS широта и долгота из метода в классе , вне переменные myLongitude и myLatitude

Вот код из MainActivity

public class MainActivity extends FragmentActivity implements ActionBar.TabListener 
{ 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //Without this, location is not fetched 
    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    LocationListener mlocListener = new MyLocationListener(); 
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 
    //mlocManager.removeUpdates(mlocListener); // This needs to stop getting the location data and save the battery power. 

    // Set up the action bar to show tabs. 
    final ActionBar actionBar = getActionBar(); 
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

    // For each of the sections in the app, add a tab to the action bar. 
    actionBar.addTab(actionBar.newTab().setText("Browse").setTabListener(this)); 
    actionBar.addTab(actionBar.newTab().setText("My City").setTabListener(this)); 
    actionBar.addTab(actionBar.newTab().setText("Search").setTabListener(this)); 
    actionBar.addTab(actionBar.newTab().setText("Favs").setTabListener(this)); 
    actionBar.addTab(actionBar.newTab().setText("Help").setTabListener(this)); 
} 


// The serialization (saved instance state) Bundle key representing the current tab position. 
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item"; 


@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) 
{ 
    // Restore the previously serialized current tab position. 
    if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) 
    { 
     getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)); 
    } 
} 


@Override 
public void onSaveInstanceState(Bundle outState) 
{ 
    // Serialize the current tab position. 
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex()); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 


//Gets the Device ID 
public String getDeviceId() 
{ 
    final String androidId, deviceId; 
    androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); 
    deviceId = androidId.toString(); 

    return deviceId; 
} 


public class MyLocationListener implements LocationListener 
{ 
    Double myLatitude; //This is passing a NULL value down to onTabSelected because it is not getting a value from onLocationChanged 
    Double myLongitude; //This is passing a NULL value down to onTabSelected because it is not getting a value from onLocationChanged 


    @Override 
    public void onLocationChanged(Location loc) 
    { 
     myLatitude = loc.getLatitude(); 
     myLongitude = loc.getLongitude(); 

     String Text = "My current location is: " + "Latitude = " + myLatitude + "Longitude = " + myLongitude; 
     Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onProviderDisabled(String provider) 
    { 
     Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onProviderEnabled(String provider) 
    { 
     Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) 
    {} 

} 


// When the given tab is selected, assign specific content to be displayed // 
@Override 
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
{ 
    Fragment fragment = new SectionFragment(); 
    Bundle args = new Bundle(); 

    final String deviceId = getDeviceId(); 


    MyLocationListener location = new MyLocationListener(); 

    final Double myLatitude = location.myLatitude; //This is returning a NULL value 
    final Double myLongitude = location.myLongitude; //This is returning a NULL value 


    //Assigns a specific URL to "ARG_SECTION_URL" for each tab 
    if(tab.getPosition()==0) 
    { 
     args.putString(SectionFragment.ARG_SECTION_URL, "http://www.myurl.com/countries.asp?Country=&State=&City=&Category=&Latitude=&Longitude=&ListingID=&AppId=aDG&DeviceID=" + deviceId + "&OrderBy=Name");   
    } 
    else if(tab.getPosition()==1) 
    { 
     args.putString(SectionFragment.ARG_SECTION_URL, "http://www.myurl.com/landing.asp?Country=&State=&City=&Category=&Latitude=" + myLatitude + "&Longitude=" + myLongitude + "&ListingID=&AppId=aDG&DeviceID=" + deviceId + "&OrderBy=Name");   
    } 
    else if(tab.getPosition()==2) 
    { 
     args.putString(SectionFragment.ARG_SECTION_URL, "http://www.myurl.com/searchform.asp?Latitude=&Longitude=&ListingID=&AppId=aDG&DeviceID=" + deviceId); 
    } 
    else if(tab.getPosition()==3) 
    { 
     args.putString(SectionFragment.ARG_SECTION_URL, "http://www.myurl.com/favorites.asp?Latitude=&Longitude=&ListingID=&AppId=aDG&DeviceID=" + deviceId + "&OrderBy=Name"); 
    } 
    else if(tab.getPosition()==4) 
    { 
     args.putString(SectionFragment.ARG_SECTION_URL, "http://www.myurl.com/help.asp?Latitude=&Longitude=&ListingID=&AppId=aDG&DeviceID=" + deviceId); 
    } 

    fragment.setArguments(args); 
    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit(); 
} 


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


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


@Override 
public void onBackPressed() 
{ 

} 


//A fragment representing a section of the app, but that simply displays content. 
public static class SectionFragment extends Fragment 
{ 
    //The fragment argument representing the section number for this fragment. 
    public static final String ARG_SECTION_URL = "section_url"; 

    public SectionFragment() 
    {} 

    @SuppressLint("SetJavaScriptEnabled") 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {   
     //Create a new WebView and set its URL to the fragment's argument value. 
     WebView myWebView = new WebView(getActivity()); 
     WebSettings webSettings = myWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 
     myWebView.loadUrl(getArguments().getString(ARG_SECTION_URL)); 
     myWebView.setWebViewClient(new MyWebViewClient()); 
     myWebView.getSettings().setAppCacheEnabled(true); 
     myWebView.getSettings().setDatabaseEnabled(true); 
     myWebView.getSettings().setDomStorageEnabled(true);  
     return myWebView; 
    } 


    private class MyWebViewClient extends WebViewClient 
    { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) 
     { 
      view.loadUrl(url); 
      return true; 
     } 

    } 

} 

} 
+0

Вы видели http://stackoverflow.com/questions/6077141/android- WebView-хау к коду-обратно кнопки? Я думаю, это может помочь. – pt2121

+0

Я видел это на самом деле, но проблема в том, что он не будет работать внутри фрагмента. –

ответ

0

Что я сделал применить его в своей деятельности, а затем иметь публичный статический так:

В основном виде деятельности:

открытый класс MainActivity расширяет FragmentActivity { public static WebView myWebView; ...

@Override 
public void onBackPressed() { 
    if (getSupportFragmentManager().findFragmentByTag("yourtag") != null) { 
     if(myWebView.canGoBack()) 
      myWebView.goBack(); 
     else { 
      super.onBackPressed(); 
     } 
    } 
    else 
     super.onBackPressed(); 
} 
... 

} и ссылаться на него в пределах фрагмента:

MainActivity.myWebView = (WebView) getView().findViewById(R.id.webview); 

и убедитесь, что при создании фрагмента добавить тег

transaction.replace(R.id.yourfragid, newfragment, "yourtag"); 
0

я нахожу это чтобы быть более простым.

В WebViewActivity.java, я добавил 1 метод:

@Override 
public void onBackPressed() { 

    WebViewFragment fragment = (WebViewFragment) 
      getSupportFragmentManager().findFragmentById(R.id.fragmentContainer); 
    if (fragment.canGoBack()) { 
     fragment.goBack(); 
    } else { 
     super.onBackPressed(); 
    } 
} 

В WebViewFragment.java, я добавил 2 метода:

public boolean canGoBack() { 
    return mWebView.canGoBack(); 
} 

public void goBack() { 
    mWebView.goBack(); 
} 
+0

Этот метод теперь поддерживается в [docs] (https://developer.android.com/training/implementing-navigation/temporal.html#back-webviews). – Keith

Смежные вопросы