退出应用程序后,在下拉导航菜单中保留一个项目

时间:2014-07-28 03:14:21

标签: android drop-down-menu android-actionbar

如果用户要从下拉导航菜单中选择一个项目,它将仅在应用程序关闭之前显示为已选中。然后,在重新打开应用程序时,它会显示所选的第一个项目。如果在活动结束后用户更改项目,我该如何永久保留项目?仅供参考我的申请中只有一项活动。

MainActivity.java

package com.student.connect;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements
        ActionBar.OnNavigationListener {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current dropdown position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    @SuppressWarnings("unused")
    private WebView student_zangle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up the action bar to show a dropdown list.
        final ActionBar actionBar = getActionBar();

        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setTitle("  ");
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setLogo(R.drawable.logo);
        actionBar.setDisplayUseLogoEnabled(true);

        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
        // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter<String>(getActionBarThemedContextCompat(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1, new String[] {
                                "Select a District",
                                "Clovis Unified",
                                "Claremont Unified",
                                "San Diego Unified",
                                "Pleasanton Unified",
                                "San Juan Unified", }), this);
    }

    /**
     * Backward-compatible version of {@link ActionBar#getThemedContext()} that
     * simply returns the {@link android.app.Activity} if
     * <code>getThemedContext</code> is unavailable.
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private Context getActionBarThemedContextCompat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return getActionBar().getThemedContext();
        } else {
            return this;
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current dropdown 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 dropdown 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.main, menu);
        return true;
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {
        WebView student_zangle = (WebView) findViewById(R.id.student_zangle);
        student_zangle.setWebViewClient( new YourWebClient());
        WebSettings settings = student_zangle.getSettings();
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowContentAccess(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);
        if ( position == 0 )
        {
            Toast.makeText(getApplicationContext(), "Select a District from the Menu Above", Toast.LENGTH_LONG).show();
        }
        else if ( position == 1 )
        {
            student_zangle.loadUrl("https://zangleweb01.clovisusd.k12.ca.us/studentconnect/");
            student_zangle.zoomOut();
            student_zangle.zoomOut();
            student_zangle.zoomOut();
        }
        else if ( position == 2 )
        {
            student_zangle.loadUrl("http://studentconnect.cusd.claremont.edu/");
        }
        else if ( position == 3 )
        {
            student_zangle.loadUrl("https://zangle.sandi.net/studentconnect/");
        }
        else if ( position == 4 )
        {
            student_zangle.loadUrl("https://sis.pleasanton.k12.ca.us/StudentPortal/");
        }
        else if ( position == 5 )
        {
            student_zangle.loadUrl("https://sis.sanjuan.edu/studentportal");
        }

        student_zangle.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); 
        settings.setUserAgentString("Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0");

        student_zangle.setDownloadListener(new DownloadListener()
        { 
            public void onDownloadStart(String url, String userAgent, 
                    String contentDisposition, String mimetype, long contentLength)
            { 
                Intent intent = new Intent(Intent.ACTION_VIEW); 
                intent.setType("application/x-rar-compressed"); 
                intent.setData(Uri.parse(url)); 
                startActivity(intent); 
            } 
        });
        return true;
    }


    @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          moveTaskToBack(true);
        }
        return super.onKeyDown(keyCode, event);
      }

    private class YourWebClient extends WebViewClient {     
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("mailto"))
            {
                String mail = url.replaceFirst("mailto:", "");
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("message/rfc822");
                intent.putExtra(Intent.EXTRA_EMAIL, mail );
                startActivity(intent);
                return true;            
            }
            view.loadUrl(url);
            return true;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

在这种情况下使用SharedPreferences

  //write your selected position in preferences when the user clicks the DropDown menu
  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
  preferences.edit().putInt("selectedPosition", selectedItemIndex).commit();

当用户返回活动(再次启动应用程序)时,您必须从首选项中读取值,如下所示:

int position = PreferenceManager.getDefaultSharedPreferences(this).getInt("selectedPosition",0);

然后只需以编程方式选择下拉菜单项。

即使应用关闭,也会保留SharedPreferences数据。因此,您可以信任它,因为它是持久数据,并且不依赖于您的应用程序状态。

请注意,如果用户取消安装应用或清除应用数据,您的偏好设置将为空。