2016-05-30 3 views
0

を使用してラジオ・グループからのラジオボタンを選択し取得し、そのフラグメントが再び起動されると、前回選択したラジオを選択しなければならない、私がしようとしたが、それを取得することができません。は入れて、選択したからラジオとラジオグループを保存するSharedPreferences

私は、ボタンのクリックで選択された位置を格納する必要があります。

これは私が使用していたコードです:

radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1); 



     radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 

      @Override 
      public void onCheckedChanged(RadioGroup group, int checkedId) { 


       // find which radio button is selected 
       if(checkedId == R.id.radioButton1) { 
        Toast.makeText(getActivity(), "You: Dude !!!", 
          Toast.LENGTH_SHORT).show(); 

       } else if(checkedId == R.id.radioButton2) { 
        Toast.makeText(getActivity(), "You: Babe !!!", 
          Toast.LENGTH_SHORT).show(); 
       } 
      } 

     }); 
+0

設定を保存してからチェックを入れてください。あなたのコードはそういうことをしません。あなたは環境設定を使ってみましたか? – Aradhna

+0

私は多方面で試してみましたが、それを理解できませんでした。サンプルコードは大いに役立ちます。 –

答えて

0

、あなたが最初にputIntまたはputStringを使用し、その後edit()タグを使用して、好みに値を追加するには、この

radiogender=(RadioGroup)rootView.findViewById(R.id.radioGroup1); 
    radioButton1=(RadioButton) rootView.findViewById(R.id.radioButton1); 
    radioButton2=(RadioButton) rootView.findViewById(R.id.radioButton2); 

    SharedPreferences myPrefs=context.getSharedPreferences("general",context.MODE_PRIVATE); //you can give any name in place of general to your preferences 

      radiogender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 

       @Override 
       public void onCheckedChanged(RadioGroup group, int checkedId) { 


        // find which radio button is selected 
        if(checkedId == R.id.radioButton1) { 
         Toast.makeText(getActivity(), "You: Dude !!!", 
           Toast.LENGTH_SHORT).show(); 

         //save in preferences 
         myPrefs.edit().putInt("selected",1).commint(); 

        } else if(checkedId == R.id.radioButton2) { 
         Toast.makeText(getActivity(), "You: Babe !!!", 
           Toast.LENGTH_SHORT).show(); 
         //save in preferences 

         myPrefs.edit().putInt("selected",2).commit(); 
        } 
       } 

      }); 

//check if there is any value in preferences and set accordingly 

int s=myPrefs.getInt("selected",0); //will return 0 when nothing is stored 
if(s==1){ 
    radioButton1.setChecked(true); 
} else if(s==2){ 
    radioButton2.setChecked(true); 
} 

のようなものを試してみてください等環境設定に価値を加える。

ここでは例putInt("selected",1);「選択された」あなたがそのキーと値を取得できるように、あなたが提供するキーまたは名前です。 「1」はそのキーに対して保存される値です。

そして、好みの値を保存するためにcommit()を使用しています。

値を取得する必要がある場合は、getIntまたはgetStringなどを使用して値を取得します。

getInt("selected",0);。ここではselectedが値を取得したいキーです。 0は、あなたが提供したキーの下の値がない場合に供給されるデフォルト値です。

希望します。

関連する問題