【问题标题】:How to put score from one activity into another activity without going to that activity?如何在不参加该活动的情况下将一项活动的分数放入另一项活动?
【发布时间】:2014-02-17 00:28:59
【问题描述】:

我正在制作一个类似于徽标测验的游戏。我有问题活动和关卡活动,所以当用户正确回答时,他们得分 1。然后我想把分数放在关卡活动中,这样用户就可以解锁下一个关卡,但我不希望用户离开问题活动,直到现在我才找到这种方法:

Intent resultIntent = new Intent(this, NextActivity.class);

resultIntent.putExtra("score", score);

startActivity(resultIntent);

但是,使用此方法,用户会转到关卡活动。

我将留下我的代码以供参考:

public class Big extends Activity {

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

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true); }

    public boolean onOptionsItemSelected(MenuItem item){
        Intent myIntent = new Intent(getApplicationContext(), Level1.class);
        startActivityForResult(myIntent, 0);
        return true;

    }


    private Button buttonSaveMem1;
    private EditText escrive; 
    private TextView respuest;
    private String [] answers;
    int score=0;
    int HighScore;

    private String saveScore = "HighScore";

    private int currentQuestion;



         public void init()
         {

            answers = new String[]{"Big"};      
            buttonSaveMem1 = (Button)findViewById(R.id.button1);     
            respuest = (TextView) findViewById(R.id.textView2); 

            escrive = (EditText) findViewById(R.id.editText1);
            buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);

            LoadPreferences();
           }

         Button.OnClickListener buttonSaveMem1OnClickListener
            = new Button.OnClickListener(){

             @Override    
                public void onClick(View arg0) {    
                    checkAnswer();


                    // TODO Auto-generated method stub
                       SavePreferences();
                       LoadPreferences();
             }};









         public boolean isCorrect(String answer)    
         {     
             return (answer.equalsIgnoreCase(answers[currentQuestion]));
             } 


         public void checkAnswer()  {     
                String answer = escrive.getText().toString();  
                if(isCorrect(answer)) {
                    update();

                    respuest.setText("You're right!" + "   The Answer is " + answer + "    your score is:" + score +"  " +
                            "HighScore:  " + HighScore);
                    score =1;



                }
                else {
                    respuest.setText("Sorry, The answer is not right!");

                }




            }
         private void update() {
         if (score > HighScore)
            { HighScore = score; }
            }


         private void SavePreferences(){
                SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("MEM1", respuest.getText().toString());
                sharedPreferences.edit().putInt(saveScore, HighScore).commit();
                editor.commit();
               }

               private void LoadPreferences(){
                SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
                String strSavedMem1 = sharedPreferences.getString("MEM1", "");
                HighScore = sharedPreferences.getInt(saveScore, 0);
                respuest.setText(strSavedMem1);

               }









    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

这是关卡活动:

public class Level extends Activity {

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


    Button salir = (Button) findViewById(R.id.button3); 
    salir.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, MainActivity.class)); }
    }
            )
            ;


Button leve2 = (Button) findViewById(R.id.button1); 
    leve2.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, Level2.class)); }
    }
            )
            ;  }   
    Button leve1 = (Button) findViewById(R.id.button1); 
    leve1.setOnClickListener( new View.OnClickListener() { 


        @Override public void onClick(View v) {
            startActivity(new Intent(Level.this, Level1.class)); }
    }
            )
            ; 



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.level, menu);
        return true;
    }

}

感谢您的帮助!

【问题讨论】:

  • 看起来您已经在使用 SharedPreferences 来保存用户的高分,为什么不使用它们来存储在问题上获得的分数,然后在用户返回级别活动时获取该分数?
  • 耶稣...请格式化您的代码。

标签: android android-activity


【解决方案1】:

在您的问题活动中,将用户的分数存储在 SharedPreferences 中

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    prefs.edit.putLong(USER_SCORE, score).commit();

然后,当您返回关卡的活动时,您可以从首选项中获取。

    SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    long userScore = prefs.getLong(USER_SCORE, 0);

USER_SCORE 只是一个字符串键,如 USER_SCORE = "user_score" 以允许设备找到您存储在首选项中的日期。

共享偏好会保存到手机中,除非通过它们所属的应用程序,否则无法访问。因此,在再次启动应用程序时,您可以获得用户上次使用应用程序时保存的分数。

【讨论】:

  • 他的要求是你不应该去其他活动看到这个变化。
  • 谢谢你帮了我很多,但现在你知道我怎样才能把所有的分数都放在一个里面吗,我试过了:SCORE = (userScore + userScore1 + userScore2) 但它不起作用
  • 每次使用 USER_SCORE 键向首选项添加分数时,它都会覆盖以前存在的数据。尝试通过从首选项中提取总分,将新分数添加到总分中,然后将其存储回首选项中,从而将总分保留在首选项中
  • 它的作品非常感谢!
【解决方案2】:

您可以将分数设为静态,然后从其他活动类对其进行修改。 IT 会自动更改原始版本。

【讨论】:

  • 将变量声明为静态并允许直接从另一个文件修改它是错误的形式。它可能会起作用,并且在小情况下很容易,但可以借给非常错误的代码,这可能是修复的噩梦。
【解决方案3】:

将分数存储在 SharedPreferences 中,而不是在意图中将其传递给 Level。然后,只要用户可以在那里导航,您就可以在 Activity 级别(或任何其他级别)中检索该分数。您已经在代码中使用 SharedPreferences:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

但是,使用调用活动的类名作为共享首选项名称返回一个共享首选项,即这些首选项值对您的“大”活动是私有的。要使用具有应用程序范围的首选项值,请使用 getSharedPreferences(),提供共享首选项名称:

SharedPreferences sharedPreferences = getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);

从中创建一个编辑器并存储“分数”的值。然后在它的 onCreate() 中检索您的关卡活动。

【讨论】:

    【解决方案4】:

    看了herethere之后,我终于通过其他答案找到了我对这个问题的答案,我基本上使用了以下代码组合来做到这一点。

    1. 在第一个活动中:

      • 导入:

        import android.content.Context;
        
        import android.content.SharedPreferences;
        
      • 声明:

        public static int totalCount;
        
      • 并添加onCreate():

        SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        
        totalCount = prefs.getInt("counter", 0);`
        totalCount++;`
        editor.putInt("counter", totalCount);`
        editor.apply();`
        
    2. 然后,在第二个活动中:

      • 导入:

        import static com.example.myapp.totalCount
        
      • 并添加onCreate():

        ((TextView) findViewById(R.id.text_view_id)).setText(String.valueOf(totalCount));
        
    3. 在第二个活动的布局中:

      • TextView 与:

        android:id="@+id/text_view_id"
        

    并关注what the documentation says about naming shared preferences

    在命名您的共享首选项文件时,您应该使用一个 您的应用程序可以唯一识别。一个简单的方法是前缀 带有您的应用程序 ID 的文件名。例如: "com.example.myapp.PREFERENCE_FILE_KEY"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多