共享首选项按钮切换

时间:2016-09-20 04:05:12

标签: android sharedpreferences

我正在尝试使用共享首选项切换按钮,这样当我打开我的应用程序时,将显示相应的按钮。 这是我设置和获取共享首选项的代码:

private void setRequestUpdatesButtonState(boolean state) {
    PreferenceManager.getDefaultSharedPreferences(this)
            .edit()
            .putBoolean(Constants.PREF_IS_BUTTON_PRESSED, state)
            .apply();
}

private boolean getRequestUpdatesButtonState() {
    return PreferenceManager.getDefaultSharedPreferences(this)
            .getBoolean(Constants.PREF_IS_BUTTON_PRESSED, false);
}

然后在onCreate方法中我检查共享首选项以显示相应的按钮:

if(getRequestUpdatesButtonState()) {
        mRequestRemoveUpdates.setCircleRadius(34);
        mRequestRemoveUpdates.setImageResource(R.drawable.ic_cancel);
    }
    else {
        mRequestRemoveUpdates.setCircleRadius(34);
        mRequestRemoveUpdates.setImageResource(R.drawable.ic_start);
    }

同样在onClick方法中,当单击按钮时,我会根据情况更改共享首选项以及按钮图像本身:

if(getRequestUpdatesButtonState()) {
      boolean updatesRequested = true;
      setRequestUpdatesButtonState(updatesRequested);
      mRequestRemoveUpdates.setCircleRadius(34);
                     mRequestRemoveUpdates.setImageResource(R.drawable.ic_cancel);
            }
else {
     boolean updatesRequested = false;
     setRequestUpdatesButtonState(updatesRequested);
     mRequestRemoveUpdates.setCircleRadius(34);
                mRequestRemoveUpdates.setImageResource(R.drawable.ic_start);
}

但它不起作用。 显然,我需要摆脱代码重复,但我想首先让它正常运行,我正在努力实现;之后我会清理它。

1 个答案:

答案 0 :(得分:0)

我不知道你的确切实现是什么,但我已经实现了你想要的类似功能。这段代码用于登录表单,布局包含两个EditText用户名和密码,记得我ImageView和登录Button。如果用户点击(检查)记住我,那么登录凭据应该保留,否则它应该不会,因此它会更改drawable ImageView 。每当用户打开应用程序时,它将在ImageView上显示正确的图像。这是使用SharedPreferences

完成的

<强> XML:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

        <EditText
            android:id="@+id/etUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:hint="Username"
            android:padding="10dp" />

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:padding="10dp" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/etPassword"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/ivRememberMe"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:layout_centerVertical="true"
                android:src="@drawable/holo_circle" />

            <TextView
                android:id="@+id/tvRememberMe"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="6dp"
                android:layout_toRightOf="@+id/ivRememberMe"
                android:text="Remember Me"
                android:textAppearance="?android:attr/textAppearanceSmall" />
        </RelativeLayout>

        <Button
            android:id="@+id/btnSignIn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:text="Sign in"
            android:textColor="@android:color/white" />
    </LinearLayout>

</RelativeLayout>

<强> MainActivity:

  public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView ivRememberMe;
    private Button btnLogin;
    private EditText etUserName, etPassword;
    private String userName, password;
    private static boolean rememberMe;
    String USERNAME = "username";
    String PASSWORD = "password";
    String REMEMBER_ME = "remember me";

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

        initValues();
    }

    private void initValues() {
        try {
            btnLogin = (Button) findViewById(R.id.btnSignIn);
            btnLogin.setOnClickListener(this);

            etUserName = (EditText) findViewById(R.id.etUserName);
            etPassword = (EditText) findViewById(R.id.etPassword);

            //Persist credentials, if remember me is checked
            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
            if (pref.contains(USERNAME) && pref.contains(PASSWORD)) {
                etUserName.setText(pref.getString(USERNAME, ""));
                etPassword.setText(pref.getString(PASSWORD, ""));
                if (pref.getBoolean(REMEMBER_ME, true)) {
                    ((ImageView) findViewById(R.id.ivRememberMe)).setImageResource(R.drawable.checkbox_marked_circle);
                }
            }
            ivRememberMe = (ImageView) findViewById(R.id.ivRememberMe);
            ivRememberMe.setOnClickListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        try {
            switch (v.getId()) {
                case R.id.btnSignIn:
                    validateCredentials();
                    onLogin();
                    break;
                case R.id.ivRememberMe:
                    rememberMe = !rememberMe;
                    ((ImageView) findViewById(R.id.ivRememberMe)).setImageResource(rememberMe ? R.drawable.checkbox_marked_circle : R.drawable.holo_circle);
                    checkPersistCredentials(etUserName.getText().toString().trim(), etPassword.getText().toString());
                    break;
                default:
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void validateCredentials() {
        try {
            userName = etUserName.getText().toString();
            password = etPassword.getText().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void onLogin() {
        //implement login request
    }


    private void checkPersistCredentials(String userName, String password) {
        rememberMe(userName, password, this);
    }

    public void rememberMe(final String username, String password, Context context) {
        try {

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            if (rememberMe) {
                if (username.isEmpty() && password.isEmpty()) {

                } else {
                    edit.putString(USERNAME, username);
                    edit.putString(PASSWORD, password);
                    edit.putBoolean(REMEMBER_ME, true);
                    edit.commit();
                }
            } else {
                edit.clear();
                edit.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

但是,您可以使用此代码来实现您的特定逻辑。