Я работаю над приложением викторины и столкнулся с основной проблемой: я хочу установить флажок, где, если оба ответа верны, оценка должна обновляться, я не знаю, где разместить код в java.
В основном так и должно работать приложение: всего вопросов 5, каждый из которых имеет 2 отметки, три MCQ, в которых один правильный, 4-й вопрос, оба ответа верны, поэтому мы добавляем флажок, каждый флажок имеет одну отметку, затем поле editText, чтобы Пользователь может добавлять свои собственные комментарии, после того как пользователь ответит на все вопросы, и только тогда, после нажатия на кнопку «Отправить», пользователю должен быть представлен рейтинг!
Спасибо
I want to know how to simply use check box to update score
Файл MainActivity.java здесь
package com.example.android.quizatlast;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int Totalscore = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//toasts , onclick , and distroying buttons for next time
final Button buttononeone = (Button) findViewById(R.id.Button1_1);
final Button buttononetwo = (Button) findViewById(R.id.Button1_2);
buttononeone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int score = 2;
Totalscore = Totalscore + score;
Score(Totalscore);
buttononeone.setEnabled(false);
buttononetwo.setEnabled(false);
}
});
buttononetwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Ahh,Wait for the score";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
buttononetwo.setEnabled(false);
buttononeone.setEnabled(false);
}
});
final Button buttontwoone = (Button) findViewById(R.id.Button2_1);
final Button buttontwotwo = (Button) findViewById(R.id.Button2_2);
buttontwoone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Dehli,City you should must visit";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
buttontwoone.setEnabled(false);
buttontwotwo.setEnabled(false);
}
});
buttontwotwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int score = 2;
Totalscore = Totalscore + score;
Score(Totalscore);
Context context = getApplicationContext();
CharSequence text = "Ahh,mumbai is a beautiful place";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
buttontwotwo.setEnabled(false);
buttontwoone.setEnabled(false);
}
});
final Button buttonthreeone = (Button) findViewById(R.id.Button3_1);
final Button buttonthreetwo = (Button) findViewById(R.id.Button3_2);
buttonthreeone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int score = 2;
Totalscore = Totalscore + score;
Score(Totalscore);
Context context = getApplicationContext();
CharSequence text = "Agra , wonders are waiting there for you";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
buttonthreeone.setEnabled(false);
buttonthreetwo.setEnabled(false);
}
});
//PROBLEM HERE
CheckBox checkBoxfourone = (CheckBox) findViewById(R.id.Checkbox4_1);
boolean check4_1 = checkBoxfourone.isChecked();
CheckBox checkBoxfourtwo = (CheckBox) findViewById(R.id.Checkbox4_2);
boolean check4_2 = checkBoxfourtwo.isChecked();
Score(Totalscore);
}
private int checkscore(boolean check4_1,boolean check4_2) {
int score = Totalscore;
if (check4_1) {
Totalscore = Totalscore + 1;
}
if (check4_2) {
Totalscore = Totalscore + 1;
}
return Totalscore;
}
//TILL HERE
public void Score(int score) {
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText(String.valueOf(score));
}public void reset(View view){
Score(Totalscore = 0);
}
}
activity_main.xml
<?xml version = "1.0" encoding = "utf-8"?>
<ScrollView
android:layout_width = "match_parent"
android:layout_height = "match_parent"
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto">
<LinearLayout
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "8dp"
android:orientation = "vertical"
tools:context = "com.example.android.justjava.MainActivity">
<LinearLayout
android:id = "@+id/topping"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:orientation = "vertical">
<EditText
android:id = "@+id/Name_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "Name"
android:inputType = "textCapCharacters" />
<EditText
android:id = "@+id/Email_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "Email"
android:inputType = "textCapCharacters" />
<TextView
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginBottom = "8dp"
android:text = "Toppings"
android:textSize = "16sp"
android:textAllCaps = "true"/>
<CheckBox
android:id = "@+id/checkbox"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Whipped Cream"
android:paddingLeft = "24dp"
android:textSize = "16sp"
android:layout_marginBottom = "8dp"/>
<CheckBox
android:id = "@+id/chocolate_checkbox"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Chocolate"
android:paddingLeft = "24dp"
android:textSize = "16sp"
android:layout_marginBottom = "8dp"/>
</LinearLayout>
<TextView
android:id = "@+id/text_view"
android:layout_below = "@id/topping"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginBottom = "8dp"
android:text = "quantity!"
android:textAllCaps = "true"
android:textSize = "16sp" />
<LinearLayout
android:id = "@+id/linear"
android:layout_below = "@id/text_view"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal"
> <Button
android:onClick = "decrement" android:id = "@+id/decrement"
android:layout_below = "@id/quantity_text_view"
android:layout_width = "48dp"
android:layout_height = "48dp"
android:text = "-"
android:layout_marginBottom = "8dp"/>
<TextView
android:layout_marginLeft = "8dp"
android:id = "@+id/quantity_text_view"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_marginBottom = "8dp"
android:layout_below = "@id/increment"
android:text = "0"
android:textColor = "#000"
android:layout_marginRight = "8dp"
android:textSize = "24sp" />
<Button
android:onClick = "increment"
android:id = "@+id/increment"
android:layout_below = "@id/text_view"
android:layout_width = "48dp"
android:layout_height = "48dp"
android:text = "+"
android:layout_marginBottom = "8dp"/>
</LinearLayout>
<TextView
android:id = "@+id/order_summary"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@id/linear"
android:layout_marginBottom = "8dp"
android:text = "order summary"
android:textAllCaps = "true"
android:textSize = "16sp" />
<TextView
android:id = "@+id/order_summary_text_view"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@id/order_summary"
android:layout_marginBottom = "8dp"
android:textSize = "24sp" />
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_below = "@id/order_summary_text_view"
android:onClick = "submitOrder"
android:text = "order" />
</LinearLayout>
</ScrollView>
Да, но есть ли способ упростить материал, я на очень базовом уровне, можем ли мы определить переменную флажка, затем использовать findviewbyid в oncreate, чтобы подключить флажок к коду, а затем создать простой метод щелчка, в котором мы обновляем результат? Приложение работает нормально до вопроса 3 о кнопке отправки, в настоящее время оценка обновляется в реальном времени под кнопкой отправки, на данный момент все в порядке, мне просто нужна помощь для флажков и редактировать текст, чтобы получить ввод от пользователя
Проверьте мой ответ ниже.
Если вы хотите подсчитать оценку только после нажатия кнопки отправки, просто переместите свой код isChecked() в свой метод submitOrder, чтобы только после того, как пользователь нажал кнопку отправки, мы проверили, установлены ли флажки или нет.
Если вы хотите обновить счет в реальном времени, следуйте ответу Рахула Чаудхари, и как только оба флажка будут отмечены, отключите оба.
Когда вы нажимаете кнопку отправки, снимите все отмеченные значения с флажка и использовать валидацию
checkValidation(){
if (checkbox1.equal(correct anwser1) && checkbox2.equal(correct anwser2)
)
{
return true
}else{
return false
}}
и отметьте при отправке
submit.setOnclick(new.....
onclick(){
if ( checkValidation()){
Toast(answer is right)
}else{
Toast(answer is wrong)
}
}
)
вы хотите проверить, устанавливаются ли флажки только при нажатии кнопки отправки?