2014-02-15 169 views
0

我正在研究一個簡單的「點擊倒數」應用程序,它基本上具有圖像按鈕
功能。
按下時它顯示的點擊從10至9%,8,7的數量,...爲0
我有一個問題,當我關閉該應用程序再次從
10.
我開始的點擊次數知道這是一個初學者的問題,但有人可以幫我嗎?
如何保存點擊次數?保存按鈕點擊數

這是我到目前爲止的代碼:

package com.example.testapp; 

import com.example.testapp.R; 

import android.os.Bundle; 
import android.app.Activity; 
import android.widget.ImageButton; 
import android.view.View; 
import android.widget.TextView; 
import android.view.View.OnClickListener; 
import com.google.ads.AdRequest; 
import com.google.ads.AdView; 

public class MainActivity extends Activity { 

    ImageButton button1; 
    TextView textView1; 
    int counter = 10; 

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

     AdView adView = (AdView)this.findViewById(R.id.adView); 
     adView.loadAd(new AdRequest()); 

     ImageButton imageButton; 
     imageButton = (ImageButton) findViewById(R.id.button1); 
     textView1 = (TextView) findViewById(R.id.textView1); 
     button1 = (ImageButton) findViewById(R.id.button1); 
     imageButton.setOnClickListener(new OnClickListener(){ 



      public void onClick(View v) { 
       if (counter >= 1) { 
        counter--; 
        textView1.setText("" + counter); 
       } else if (counter == 0){ 
        button1.setImageResource(R.drawable.picture2); 
        counter--; 

       } 


      } 
     }); 
    } 

} 
+1

店它的默認值:) –

回答

1

看一看SharedPreferences。他們將允許您保存會話之間的數據:

E.g.

在啓動時:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 
clickCount = sharedPreferences.getInt("Click_Count", 0); 

節能:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 
Editor editor = sharedPreferences.edit(); 
editor.putInt("Click_Count", clickCount); 
editor.commit(); 
0

可以在SharedPreferences保存您的計數值如下...

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); 
SharedPreferences.Editor prefsEditor = prefs.edit(); 

public void onClick(View v) { 
    if (counter >= 1) { 
     counter--; 
     textView1.setText("" + counter); 

     prefsEditor.putInt("counter", counter); 
     prefsEditor.commit(); 

    } else if (counter == 0){ 
     button1.setImageResource(R.drawable.picture2); 
     counter--; 

     prefsEditor.putInt("counter", counter); 
     prefsEditor.commit(); 

    } 
} 

檢索SharedPreferences作爲計數器值以下...

counter = prefs.getInt("counter", 10); 

現在,如果它不能在與鍵「計數器」 SharedPreferences覺得值,那麼它會返回一個`sharedpreference`的10