共享偏好:浮动

时间:2015-12-17 13:38:11

标签: android android-sharedpreferences

它出了什么问题

package com.sahandxx3.Countries;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

/**
 * Created by Setude on 17-Dec-15.
 */
public class Setting extends Activity {
    SharedPreferences sh;
    TextView txtflag,txt_test;
    SeekBar sbflag;
    int progress = 10;
    float size=10;
    float txt_size;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        init();
        txtflag.setText("Flag size : "+sbflag.getProgress());

        sbflag.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                txt_size=sh.getFloat("size",0);
                progress= i;
                size=(progress*5)+5;
                txtflag.setText("Flag size : "+progress);
                txt_test.setTextSize(size);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

                txtflag.setText("Flag size : "+progress);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                txtflag.setText("Flag size : "+progress);
                sh=PreferenceManager.getDefaultSharedPreferences(Setting.this);
                SharedPreferences.Editor edit=sh.edit();
                edit.putFloat("size",size);
                edit.commit();
            }
        });
    }
    private void init() {
        txtflag= (TextView) findViewById(R.id.txtflag);
        sbflag= (SeekBar) findViewById(R.id.sbflag);
        txt_test= (TextView) findViewById(R.id.btn_test);
    }
}

所以我的问题在于这一行:

 txt_size=sh.getFloat("size",0);

当我尝试更改搜索栏时,它会停止工作。

然后我想在txt_test();

中使用txt_size

3 个答案:

答案 0 :(得分:2)

我最好的猜测是,您尝试访问它时,SharedPreferences实例sh为空。尝试将sh=PreferenceManager.getDefaultSharedPreferences(Setting.this);移至onCreate()

答案 1 :(得分:0)

我认为你应该使用

 float size=10f;
 txt_size=sh.getFloat("size",0f);

答案 2 :(得分:0)

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);
    sh=PreferenceManager.getDefaultSharedPreferences(this);
}