检查输入的答案是否与数组xml android匹配

时间:2014-08-26 09:40:41

标签: android arrays

我正在创建一个测验,我有一个Question的文本视图,一个回答的文本域,以及一个检查答案是对还是错的按钮。我有2个xml文件,一个用于问题数组,另一个用于答案数组。

public class ArrayAct extends Activity{
Button mButton;
EditText mEdit;
String [] mArray;
String [] mArray1;

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


    mArray = getResources().getStringArray(R.array.Answers);
    mArray1 = getResources().getStringArray(R.array.Questions);

    final Button doneBtn = (Button)findViewById(R.id.doneBtn);
    final EditText text = (EditText)findViewById(R.id.txtFld);

    doneBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (Arrays.asList(mArray).contains(text.getText().toString()))
                Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_SHORT).show();
            else 
                Toast.makeText(getApplicationContext(), "Incorrect.Please try again.", Toast.LENGTH_SHORT).show();

        }
    });

    TextView textView = (TextView)findViewById(R.id.txtView); 
    Random random = new Random();

    int maxIndex = mArray1.length;
    int generatedIndex = random.nextInt(maxIndex);

    textView.setText(mArray1[generatedIndex]);   
}

}

我应该实施什么代码,以便检查输入的答案是否与问题的正确答案相符?

1 个答案:

答案 0 :(得分:1)

请尝试这种方式,希望这有助于您解决问题。

public class ArrayAct extends Activity {

    private Button doneBtn;
    private EditText text;
    private TextView textView;
    private String [] mArray;
    private String [] mArray1;
    private int generatedIndex;

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

        textView = (TextView)findViewById(R.id.txtView);
        doneBtn = (Button)findViewById(R.id.doneBtn);
        text = (EditText)findViewById(R.id.txtFld);

        mArray = getResources().getStringArray(R.array.Answers);
        mArray1 = getResources().getStringArray(R.array.Questions);

        doneBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mArray[generatedIndex].equals(text.getText().toString()))
                    Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(getApplicationContext(), "Incorrect.Please try again.", Toast.LENGTH_SHORT).show();

            }
        });

        Random random = new Random();

        generatedIndex = random.nextInt(mArray1.length);
        textView.setText(mArray1[generatedIndex]);
    }
}