Android Studio测验应用程序保存分数

时间:2017-01-06 17:48:59

标签: android android-layout android-studio android-framelayout

我目前正在制作一个标记测验应用,并希望添加分数。下面你可以看到它的图片;每个标志都是一个片段,按下它们时,右侧允许您提交答案。

enter image description here

当您输入正确答案时,"正确"消息出现,您可以转到下一个标志。我想要一个正确的答案给出1分,错误的分数(或者当按下跳过或提示时)得分为零。最后,总结了得分。但是,我不确定如何做到这一点。我已经创建了一个ScoreActivity.java文件,其中的分数将被注册(虽然它当前是空的),我已经尝试编写如下所示的代码。

Play.java

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.app.FragmentManager;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.ViewGroup;


import layout.FragmentOne;
import layout.FragmentTwo;
import layout.FragmentThree;
import layout.FragmentDefault;


public class Play extends MainActivity {


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


    final ImageButton imageBtn10 = (ImageButton) findViewById(R.id.imageButton10);
    final ImageButton imageBtn9 = (ImageButton) findViewById(R.id.imageButton9);
    final ImageButton imageBtn8 = (ImageButton) findViewById(R.id.imageButton8);
    final ImageButton imageBtn7 = (ImageButton) findViewById(R.id.imageButton7);
    final ImageButton imageBtn6 = (ImageButton) findViewById(R.id.imageButton6);
    final ImageButton imageBtn5 = (ImageButton) findViewById(R.id.imageButton5);
    final ImageButton imageBtn4 = (ImageButton) findViewById(R.id.imageButton4);
    final ImageButton imageBtn3 = (ImageButton) findViewById(R.id.imageButton3);

    FragmentManager fragMan = getFragmentManager();
    FragmentTransaction fragTrans = fragMan.beginTransaction();
    FragmentDefault fd = new FragmentDefault();
    fragTrans.replace(R.id.fragment_place, fd);
    fragTrans.commit();

    fragTrans.hide(new FragmentOne());
    fragTrans.hide(new FragmentTwo());
    fragTrans.hide(new FragmentThree());

    imageBtn10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                FragmentManager fragMan = getFragmentManager();
                FragmentTransaction fragTrans = fragMan.beginTransaction();
                fragTrans.replace(R.id.fragment_place, new FragmentOne());
                fragTrans.commit();
                imageBtn10.setEnabled(false);
        }

    });


    imageBtn9.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentTwo());
            fragTrans.commit();
        }
    });

    imageBtn8.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
                FragmentManager fragMan = getFragmentManager();
                FragmentTransaction fragTrans = fragMan.beginTransaction();
                fragTrans.replace(R.id.fragment_place, new FragmentThree());
                fragTrans.commit();
        }
    });

    imageBtn7.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn6.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn5.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    imageBtn4.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
            //imageBtn4.setEnabled(false);
        }
    });

    imageBtn3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fragMan = getFragmentManager();
            FragmentTransaction fragTrans = fragMan.beginTransaction();
            fragTrans.replace(R.id.fragment_place, new FragmentThree());
            fragTrans.commit();
        }
    });

    Button button_score = (Button)findViewById(R.id.scoreButton);
    button_score.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentPlay = new Intent(Play.this, ScoreActivity.class);
            startActivity(intentPlay);
        }
    });



}




}

FragmentOne.java (这是德国国旗的片段)

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
 import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
//import android.widget.TextView;


public class FragmentOne extends Fragment {

EditText theAnswer;
Button ScoreButton;

private EditText userAnswer;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_fragment_one, null);
    userAnswer = (EditText)v.findViewById(R.id.editText);
    final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
    final TextView hintv = (TextView)v.findViewById(R.id.textHint);


    final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");

            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

    final Button skip = (Button)v.findViewById(R.id.skipBtn);
    skip.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            submit.setEnabled(false);
        }
    });

    final Button hint = (Button)v.findViewById(R.id.hintBtn);
    hint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
            //submit.setEnabled(false);
        }
    });


    return v;


}

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    ScoreButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            SharedPreferences.Editor editor = app_preferences.edit();

            if (userAnswer.isChecked()){
                editor.putInt("answer_value", 1);
            }
            else {
                editor.putInt("answer_value", 0);
            }
            editor.commit();
        }
    });
}



}

.isChecked()显示为红色。我需要导入一些东西吗?

3 个答案:

答案 0 :(得分:2)

首先:你为什么要使用所有这些片段?您不能使用单个片段更新其数据以在问题之间交替吗?

问题是EditText类没有isChecked()方法。 要使用该方法,您需要使用CheckBox类。

您正在使用窗口小部件来捕获用户输入,例如文本类型HTML input。 被检查在逻辑上是可以检查的项目的属性,如HTML checkbox

您正在将文本放入EditText(用户答案),然后如果选中了字符串容器字段,则会询问它。这没有意义。

如果用户回答匹配正确答案(如布尔值),您真正需要的是存储。在结果TextView中设置“正确”时可以设置此值,如下所示:

final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");
                // keep trace of user answer result
                wellAnswered = true;
            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

然后您可以按如下方式更新FragmentOne代码:

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    ScoreButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            SharedPreferences.Editor editor = app_preferences.edit();

            if (wellAnswered){
                editor.putInt("answer_value", 1);

                // remember to reset your variable for next question
                wellAnswered = false;
            }
            else {
                editor.putInt("answer_value", 0);
            }
            editor.commit();
        }
    });
}

答案 1 :(得分:0)

要保存分数,您可以使用SharedPreferences。根据文档:

  

如果您要保存的密钥值集合相对较少,则应使用SharedPreferences API。 SharedPreferences对象指向包含键值对的文件,并提供读取和写入它们的简单方法。每个SharedPreferences文件都由框架管理,可以是私有的或共享的。

如何使用SharedPreferences存储我的分数?

每次用户点击submit按钮时,onClickListener()内部都会检索SharedPreferences文件中的现有值并将其递增一个。

那么,我该怎么办?

首先,创建一个SharedPreferences

的实例
private SharedPreferences sharedpreferences;

然后初始化它:

sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);

然后在onClickListener()

SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("SCORE", sharedpreferences.getInt("SCORE",0)+1);
editor.apply();

这样做的是,它会创建一个Key值对,其中键为SCOREputInt()方法会插入与该键相关联的值,在本例中为SCORE

注意sharedpreferences.getInt("SCORE",0)+1)这样做会增加,得分为1。最后apply()将数据保存到SharedPreferences文件中。

如何检索分数?

sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
int score = sharedpreferences.getInt("SCORE",0)

其中,0是默认值。

<小时/> 希望它有所帮助!

答案 2 :(得分:0)

所以我修改了FragmentOne.java中的代码,现在它看起来像这样:

public class FragmentOne extends Fragment {

private EditText userAnswer;
private boolean wellAnswered;
private Button ScoreButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_fragment_one, null);
    userAnswer = (EditText)v.findViewById(R.id.editText);
    final TextView tv = (TextView)v.findViewById(R.id.showCorrect);
    final TextView hintv = (TextView)v.findViewById(R.id.textHint);

    final Button submit = (Button)v.findViewById(R.id.submitBtn1);
    submit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String theAnswer = (userAnswer.getText().toString());
            if (theAnswer.equalsIgnoreCase("Germany")) {
                //TextView tv = (TextView)v.findViewById(R.id.showCorrect);
                tv.setText("Correct!");
                wellAnswered = true;

            } else {

            }
            submit.setEnabled(false);

            // updateScore();
        }
    });

    final Button skip = (Button)v.findViewById(R.id.skipBtn);
    skip.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            submit.setEnabled(false);
        }
    });

    final Button hint = (Button)v.findViewById(R.id.hintBtn);
    hint.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            hintv.setText("The capital is Berlin \n The country is in Europe \n It starts with G... ");
            //submit.setEnabled(false);
        }
    });


    return v;}

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ScoreButton = (Button)getView().findViewById(R.id.scoreButton);


        final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        ScoreButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SharedPreferences.Editor editor = app_preferences.edit();

                if (wellAnswered){
                    editor.putInt("answer_value", 1);

                    // remember to reset your variable for next question
                    wellAnswered = false;
                }
                else {
                    editor.putInt("answer_value", 0);
                }
                editor.commit();
            }
        });
    }



}

我已经使用了你的答案中的建议而没有错误,但是,当我按下标记时应用程序崩溃了。知道我做错了吗?

<强>栈跟踪

01-06 20:08:18.152 3912-3912/? I/art: Not late-enabling -Xcheck:jni (already on)
01-06 20:08:18.153 3912-3912/? W/art: Unexpected CPU variant for X86 using defaults: x86
01-06 20:08:18.189 3912-3919/? I/art: Debugger is no longer active
01-06 20:08:18.189 3912-3919/? I/art: Starting a blocking GC Instrumentation
01-06 20:08:18.294 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.299 3912-3912/? I/InstantRun: Instant Run Runtime started. Android package is com.example.karolinawullum.quizapp, real application class is null.

                                             [ 01-06 20:08:18.311  1560: 1583 D/         ]
                                             HostConnection::get() New Host Connection established 0x8d661580, tid 1583
01-06 20:08:18.378 3912-3912/? W/System: ClassLoader referenced unknown path: /data/app/com.example.karolinawullum.quizapp-1/lib/x86
01-06 20:08:18.487 3912-3912/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
01-06 20:08:18.608 3912-3933/? I/OpenGLRenderer: Initialized EGL, version 1.4
01-06 20:08:18.610 3912-3933/? D/OpenGLRenderer: Swap behavior 1
01-06 20:08:18.637 3912-3933/? E/EGL_emulation: tid 3933: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
01-06 20:08:18.637 3912-3933/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x90557900, error=EGL_BAD_MATCH