按下按钮后在文本小部件中显示分数

时间:2015-10-31 16:43:11

标签: java android

我正在制作一个基本的Q&一个应用程序勾选一个答案后,将分数增加x。我希望在按下按钮时,分数显示在底部文本小部件“得分”中。我怎样才能做到这一点?

我的java代码是:

> x <- -5
> if(x > 0){
+     print("Non-negative number")
+ } else{
+     print("Negative number")
+ }
[1] "Negative number"

这是我的xml代码:

public class MainActivity extends AppCompatActivity {

public int score = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    question1();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void question1(){
    String Question1 = "Question 1";

    TextView t = (TextView) findViewById(R.id.Question);
    TextView A = (TextView) findViewById(R.id.AnswerA);
    TextView B = (TextView) findViewById(R.id.AnswerB);
    TextView C = (TextView) findViewById(R.id.AnswerC);
    TextView D = (TextView) findViewById(R.id.AnswerD);
    TextView Score = (TextView) findViewById(R.id.Score);

    t.setText("Question 1");
    A.setText("Answer A");
    B.setText("Answer B");
    C.setText("Answer C");
    D.setText("Answer D");
    Score.setText(score);
}

public int onCheckboxClickedA(){
    return score = score + 1;
}
public int onCheckboxClickedB(){
    return score = score + 2;
}
public int onCheckboxClickedC(){
    return score = score + 3;
}
public int onCheckboxClickedD(){
    return score = score + 4;
    }
}

1 个答案:

答案 0 :(得分:0)

首先在方法问题1()

 Score.setText(String.valueOf(score));

其次,在活动中创建对按钮的引用

  Button b = (Button)findViewById(R.id.button);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Score.setText(String.valueOf(score));
        }
    });

第三,创建分数的最终对象。

  final  TextView Score = (TextView) findViewById(R.id.Score);