2016-05-15 139 views
0

我是一個新的android應用程序開發人員。我正在製作一個應用程序,我想使用共享偏好來存儲餘額整數,但我不知道如何去做。我做了大量的谷歌搜索,但我仍然感到困惑。任何人都可以請把共享首選項存儲在我的代碼中的平衡整數?這是代碼。Android工作室共享喜好存儲到設備存儲

import android.content.SharedPreferences; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.view.WindowManager; 
import android.widget.ImageButton; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity { 
    int balance = 0; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     //Hide notification bar 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     //Click counter 
     final TextView text = (TextView) findViewById(R.id.balance_text); 
     assert text != null; 
     text.setText(balance + " $"); 
     final ImageButton button = (ImageButton) findViewById(R.id.click_button); 
     assert button != null; 
     button.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       balance++; 
       text.setText("" + balance + " $"); 
      } 
     }); 
    } 

} 

回答

2

請找到下面的代碼從sharedpreferences

public class MainActivity extends AppCompatActivity { 
int balance;; 
private SharedPreferences preferences; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    //Hide notification bar 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    //Click counter 
    final TextView text = (TextView) findViewById(R.id.balance_text); 
    assert text != null; 
    // to retreuve the values from the shared preference 
    preferences = PreferenceManager.getDefaultSharedPreferences(this); 
    balance = preferences.getInt("balance", 0); 
    text.setText(balance + " $"); 
    final ImageButton button = (ImageButton) findViewById(R.id.click_button); 
    assert button != null; 
    button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      balance++; 
      text.setText("" + balance + " $"); 
     } 
    }); 
} 

}

獲取值使用這些線將其保存到共享的偏好。你可以使用onBackPressed()

@Override 
public void onBackPressed() { 
    super.onBackPressed(); 
    SharedPreferences.Editor editor = preferences.edit(); 
     editor.putInt("balance", balance); 
     editor.apply(); 
} 
+0

謝謝!有用! – Camper1233

+0

請導入類.. import android.preference.PreferenceManager; import android.content.SharedPreferences; – somia

+0

還有一件事我需要,請你向我解釋如何使用onBackPressed()或者只是給我我需要放入的代碼。謝謝。 – Camper1233