Android:onBackPressed()用于片段中的Web视图

时间:2013-03-25 18:17:21

标签: android webview gps fragment

我是一位相对较新的Android开发者,目前正在完成我的第一款Android应用。

这个应用程序是一个Web应用程序的“shell”应用程序,它使用片段,但我有两个问题。我做了大量的研究,但我无法得到任何我发现的想法,所以我希望我能在这里得到一些答案。提前谢谢!

1)我希望用户能够使用他们设备上的后退按钮返回Web视图

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;
        }

    }

}

}

3 个答案:

答案 0 :(得分:1)

我发现这种方式更简单。

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中,我添加了两种方法:

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

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

答案 1 :(得分: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");

答案 2 :(得分:0)

  1. 使用WebView在代码段中实现View.OnKeyListener;

    public class ItemMenuFragment extends Fragment implementsView.OnKeyListener
    
  2. 将onKeyListener侦听器连接到WebView;

    webView.setOnKeyListener(this);
    
  3. 重写OnKeyListener.onKey方法;

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == MotionEvent.ACTION_UP && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }