Android开发小项目_2、猜数字游戏
界面Preview
实现方式:拖动Platte
对每个组件进行命名
Java活动代码
package com.example.guess_num;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int points;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pickrandom();
}
private void pickrandom(){
Random randy = new Random();
int rand1 = randy.nextInt(10);
int rand2 = 0;
rand1 = randy.nextInt(10);
while (true){
rand2 = randy.nextInt(10);
if(rand2 != rand1) break;
}
rand2 = randy.nextInt(10);
Button lbutt =(Button) findViewById(R.id.button_1);
lbutt.setText(Integer.toString(rand1));
Button rbutt =(Button) findViewById(R.id.button_2);
rbutt.setText(Integer.toString(rand2));
}
public void rightButton(View view) {
Button lbutt = (Button) findViewById(R.id.button_1);
String ltext = lbutt.getText().toString();
int rand1 = Integer.parseInt(ltext);
Button rbutt = (Button) findViewById(R.id.button_2);
String rtext = rbutt.getText().toString();
int rand2 = Integer.parseInt(rtext);
if(rand1 <= rand2){
points++;
Toast.makeText(this,"Great Job!",Toast.LENGTH_SHORT).show();
}else{
points--;
Toast.makeText(this,"You Suck",Toast.LENGTH_SHORT).show();
}
TextView tv = (TextView) findViewById(R.id.bottom_text);
tv.setText("Points:" + points);
pickrandom();
}
public void leftButton(View view) {
Button lbutt = (Button) findViewById(R.id.button_1);
String ltext = lbutt.getText().toString();
int rand1 = Integer.parseInt(ltext);
Button rbutt = (Button) findViewById(R.id.button_2);
String rtext = rbutt.getText().toString();
int rand2 = Integer.parseInt(rtext);
if(rand1 <= rand2){
points++;
Toast.makeText(this,"Great Job!",Toast.LENGTH_SHORT).show();
}else{
points--;
Toast.makeText(this,"You Suck",Toast.LENGTH_SHORT).show();
}
TextView tv = (TextView) findViewById(R.id.bottom_text);
tv.setText("Points:" + points);
pickrandom();
}
}
注:部分代码解释
TextView tv = (TextView) findViewById(R.id.bottom_text);