SharedPreferences明显的行为

时间:2016-06-05 22:50:38

标签: android android-fragments sharedpreferences typeface

我是Android开发人员的初学者,我正在创建一个内容很简单的应用程序,你可以使用设置片段编辑内容的字体类型和大小。 我面临一个问题,当我设置我的字体设置时,它保存得很好。我关闭应用程序并返回内容活动,它工作得很好,但当我回到设置片段时,它返回字体类型JUST。到默认值。字体大小保持在用户确定的值。 这是设置片段代码

    package com.example.ali.azkarv10;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.preference.SwitchPreference;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SettingsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SettingsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingsFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private static final String fonts[]={"fonts/blacksugar.ttf","fonts/baghdad.ttf","fonts/bdavat.ttf","fonts/fsmetal.ttf","fonts/kufi.ttf","fonts/tachkili.ttf","fonts/yassin.ttf"};
    private String mParam1;
    private String mParam2;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor edit;
    Switch switchWidget;
    TextView textView;
    SeekBar seekBar;
    TextView tester;
    Spinner spinner;
    SpinnerAdapter spinnerAdapter;
    private OnFragmentInteractionListener mListener;

    public SettingsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingsFragment newInstance(String param1, String param2) {
        SettingsFragment fragment = new SettingsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
        edit=sharedPreferences.edit();
        View v= inflater.inflate(R.layout.fragment_settings, container, false);
        switchWidget=(Switch)v.findViewById(R.id.switch1);
        switchWidget.setChecked(sharedPreferences.getBoolean("buzzer",false));
        switchWidget.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                   edit.putBoolean("buzzer",true);
                   // Toast.makeText(getActivity(),"true",Toast.LENGTH_LONG).show();
                    edit.commit();
                }else {
                    edit.putBoolean("buzzer",false).commit();
                    //Toast.makeText(getActivity(),"false",Toast.LENGTH_LONG).show();

                }

            }
        });

        tester=(TextView)v.findViewById(R.id.textSizeTester);
        seekBar=(SeekBar)v.findViewById(R.id.seekBar);
        seekBar.setProgress(sharedPreferences.getInt("fontSize",20)-10);
        tester.setTextSize(seekBar.getProgress()+10);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            int progress_Value;
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress_Value=progress;
                edit.putInt("fontSize",10+progress).commit();
                tester.setTextSize(((float)10+progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                edit.putInt("fontSize",10+progress_Value).commit();
                tester.setTextSize(((float)10+progress_Value));
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                edit.putInt("fontSize",10+progress_Value).commit();
                tester.setTextSize(((float)10+progress_Value));

            }
        });

        Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
        textView=(TextView)v.findViewById(R.id.textsets);
        textView.setTypeface(typeface);
        spinner=(Spinner)v.findViewById(R.id.spinner);
        spinnerAdapter=new SpinnerAdapter(getActivity(),fonts);
        spinner.setAdapter(spinnerAdapter);
        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","fonts/fsmetal.ttf")));

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch(position){
                    case 0:edit.putString("fontType",fonts[0]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
                        break;
                    case 1:edit.putString("fontType",fonts[1]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 2:edit.putString("fontType",fonts[2]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 3:edit.putString("fontType",fonts[3]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 4:edit.putString("fontType",fonts[4]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 5:edit.putString("fontType",fonts[5]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;
                    case 6:edit.putString("fontType",fonts[6]).commit();
                        tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                        break;


                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
       // textView.setText(sharedPreferences.getString("fontType",""));
        return v;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

请帮助

2 个答案:

答案 0 :(得分:1)

第一次使用onItemSelectedListener调用

position = 0

因此,在创建SettingsFragment时,您将使用"fonts/blacksugar.ttf"覆盖首选项。

您应该获得“fontType”首选项并在Spinner中选择它:

    Spinner spinner = (Spinner) v.findViewById(R.id.spinner);
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_layout, fonts);
    spinner.setAdapter(spinnerAdapter);

    spinner.setSelection(spinnerAdapter.getPosition(sharedPreferences.getString("fontType","fonts/blacksugar.ttf")));
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            edit.putString("fontType",fonts[position]).commit();
            tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

答案 1 :(得分:0)

    Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(),"fonts/blacksugar.ttf");
    textView=(TextView)v.findViewById(R.id.textsets);
    textView.setTypeface(typeface);

我认为你的问题可能就在这里。您自己设置textview的字体,而不是从文件中读取。

此外,

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch(position){
                case 0:edit.putString("fontType",fonts[0]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));
                    break;
                case 1:edit.putString("fontType",fonts[1]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;
                case 2:edit.putString("fontType",fonts[2]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;
                case 3:edit.putString("fontType",fonts[3]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;
                case 4:edit.putString("fontType",fonts[4]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;
                case 5:edit.putString("fontType",fonts[5]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;
                case 6:edit.putString("fontType",fonts[6]).commit();
                    tester.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),sharedPreferences.getString("fontType","")));

                    break;


            }
        }

switch语句是多余的。只是做,

edit.putString("fontType",fonts[position]).commit();