测验申请?

时间:2017-10-25 19:01:15

标签: android

我正在为我的项目构建一个测验应用程序。我对不同的问题有不同的活动。我用单选按钮来寻找答案。请问如何设置一个将分数添加到初始分数的计数器?我应该在哪里定义柜台?以及如何在不同布局的每次点击上获得响应? 这就是我所拥有的

package com.example.android.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

    enter code here

public class page1 extends AppCompatActivity {

    @Override
int score = 0;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page1);

    }
    public void pageTwo(View view) {

        Intent i = new Intent(this,page2.class);
        startActivity(i);

    }
    public void ans(View view)
    {

        Toast.makeText(this,score,Toast.LENGTH_SHORT).show();
    } 
}

1 个答案:

答案 0 :(得分:0)

解决方案1:

使用SharedPreferences存储分数的整数:

SharedPreferences sp = getSharedPreferences("data", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("score", score);
editor.apply();

要获得其他活动的分数:

SharedPreferences sp = getSharedPreferences("data", Activity.MODE_PRIVATE);
int score = sp.getInt("score", 0); //0 for default if score do not exist.

但是,即使用户退出应用程序,该变量仍然存在。

解决方案2:

在活动之间传递数据:

Intent i = new Intent(ActivityName.this, NewActivityName.class);
i.putExtra("extra", score);
startActivity(i);

在新活动中:

int score = getIntExtra("extra", 0); //0 for default if score do not exist.

使用此方法,如果用户退出应用,您将无法保存分数。

相关问题